如何将PHP数组转换为关联数组

时间:2018-07-12 09:27:18

标签: php

我想根据数组值转换此数组。

在将下划线值转换为键之前和在将'_”值转换为值之后

原始数组

Array ( 
  [0] => 1_1 
  [1] => 1_2 
  [2] => 1_3 
  [3] => 1_4 
  [4] => 1_5 
  [5] => 1_6 
  [6] => 3_1 
  [7] => 3_2 
  [8] => 3_4 
  [9] => 3_5 
  [10] => 4_1 
  [11] => 4_2 
  [12] => 4_3 
) 

我想将其转换为:

Array(
  [1]=> array(
    [0]=>1,
    [1]=>2,
    [2]=>3,
    [3]=>4,
    [4]=>5,
    [5]=>6
  ),
  [3]=> array(
    [0]=>1,
    [1]=>2,
    [2]=>4,
    [3]=>5,
    [4]=>5
  ),
  [4]=> array(
    [0]=>1,
    [1]=>2,
    [2]=>3
  )
);

2 个答案:

答案 0 :(得分:1)

这应该可以完成工作:

$array = Array (
  0  => "1_1",
  1  => "1_2",
  2  => "1_3",
  3  => "1_4",
  4  => "1_5",
  5  => "1_6",
  6  => "3_1",
  7  => "3_2",
  8  => "3_4",
  9  => "3_5",
  10 => "4_1",
  11 => "4_2",
  12 => "4_3"
);

// Create a new empty array
$result = array();

// Loop throught your first array
foreach ($array as $data) {

    // Foreach data, you explode by '_'so you will get an array
    // Eg. $new_data = array(0 => '1', 1 => '1') for $data = "1_1"
    $new_data = explode('_', $data);

    // Now you just have to add the data as you want
    $result[$new_data[0]][] = $new_data[1];
}

var_dump($result);

输出为:

array (size=3)
1 => 
array (size=6)
  0 => string '1' (length=1)
  1 => string '2' (length=1)
  2 => string '3' (length=1)
  3 => string '4' (length=1)
  4 => string '5' (length=1)
  5 => string '6' (length=1)
3 => 
array (size=4)
  0 => string '1' (length=1)
  1 => string '2' (length=1)
  2 => string '4' (length=1)
  3 => string '5' (length=1)
4 => 
array (size=3)
  0 => string '1' (length=1)
  1 => string '2' (length=1)
  2 => string '3' (length=1)

答案 1 :(得分:0)

这应该有效:

$resp = [];
foreach ($arr as $a) {
    $values = explode('_', $a);

    $resp[$values[0]][] = $values[1]; 
}

反之:

$resp = [];
foreach ($resp as $key => $arr) {
    foreach ($arr as $a) {
        $resp[] = $key . '_' . $a;
    }
}