如何使用 php 将多维数组的数组替换为该数组的项目?
How to replace arrays of multidimensional array with items of that array using php?
在下面的多维数组中,我如何用 [SUB1]
[=19= 中的相应值替换顶级索引 [0]
[1]
& [2]
]
Array
(
[0] => Array
(
[SUB1] => AAA111
[SUB2] => Description 1
[SUB3] => 10
)
[1] => Array
(
[SUB1] => BBB222
[SUB2] => Description 2
[SUB3] => 20
)
[2] => Array
(
[SUB1] => CCC333
[SUB2] => Description 3
[SUB3] => 30
)
)
我已经设法使用 $sub1 = array_column( $array, 'SUB1' );
获得了下面的数组,但我不确定是否存在一个简单的函数来使用它来用值替换原始数组中的索引。
Array
(
[0] => AAA111
[1] => BBB222
[2] => CCC333
)
编辑:
期望的输出:
Array
(
[AAA111] => Array
(
[SUB2] => Description 1
[SUB3] => 10
)
[BBB222] => Array
(
[SUB2] => Description 2
[SUB3] => 20
)
[CCC333] => Array
(
[SUB2] => Description 3
[SUB3] => 30
)
)
请检查下面的示例,其中 $test 等于您的主数组。
$output = [];
foreach ($test as $t) {
$first = reset($t);
$remaining = array_shift($t);
$output[$first] = $t;
}
echo '<pre>';
print_r($output);
在下面的多维数组中,我如何用 [SUB1]
[=19= 中的相应值替换顶级索引 [0]
[1]
& [2]
]
Array
(
[0] => Array
(
[SUB1] => AAA111
[SUB2] => Description 1
[SUB3] => 10
)
[1] => Array
(
[SUB1] => BBB222
[SUB2] => Description 2
[SUB3] => 20
)
[2] => Array
(
[SUB1] => CCC333
[SUB2] => Description 3
[SUB3] => 30
)
)
我已经设法使用 $sub1 = array_column( $array, 'SUB1' );
获得了下面的数组,但我不确定是否存在一个简单的函数来使用它来用值替换原始数组中的索引。
Array
(
[0] => AAA111
[1] => BBB222
[2] => CCC333
)
编辑:
期望的输出:
Array
(
[AAA111] => Array
(
[SUB2] => Description 1
[SUB3] => 10
)
[BBB222] => Array
(
[SUB2] => Description 2
[SUB3] => 20
)
[CCC333] => Array
(
[SUB2] => Description 3
[SUB3] => 30
)
)
请检查下面的示例,其中 $test 等于您的主数组。
$output = [];
foreach ($test as $t) {
$first = reset($t);
$remaining = array_shift($t);
$output[$first] = $t;
}
echo '<pre>';
print_r($output);