我有一个像这样的数组
$myArray = [
[
'key1' => $val1,
'key2' => $val2,
'key3' => $val3,
],
[
'key1' => $val4,
'key2' => $val5,
'key3' => $val6,
],
];
我想将$myArray
转换成这样的关联数组
$myArray = [
$val3 => [
'key1' => $val1,
'key2' => $val2,
'key3' => $val3,
],
$val6 =>[
'key1' => $val4,
'key2' => $val5,
'key3' => $val6,
],
];
是否有php函数或功能组合为您完成?
答案 0 :(得分:1)
也许是这样吗?
function conv_arr($arr) {
$newArr = [];
foreach ($arr as $r) {
$newArr[end($r)] = $r;
}
return $newArr;
}
答案 1 :(得分:1)
如果要使用每个数组的最后一个array
获取一个新的key
,请尝试以下操作:
<?php
$new = array();
$myArray = [
[
'key1' => 1,
'key2' => 2,
'key3' => 3,
],
[
'key1' => 4,
'key2' => 5,
'key3' => 6,
],
];
foreach( $myArray as $array ){
end($array);
$key = key($array);
$new[$array[$key]] = $array;
}
print_r($new);
仅使用foreach
。
答案 2 :(得分:1)
单线,以更好地理解以下几行内容:
print_r(
array_combine(
array_column($myArray, 'key3'),
$myArray
)
);
答案 3 :(得分:0)
如果您的示例输出说明了您打算使用的模式,则可以将此示例用作指导。请查看评论以获取逐步说明。
<?php
// Your variables defined.
$val1 = 1;
$val2 = 2;
$val3 = 3;
$val4 = 4;
$val5 = 5;
$val6 = 6;
// Your input array.
$myArray = [
[
'key1' => $val1,
'key2' => $val2,
'key3' => $val3,
],
[
'key1' => $val4,
'key2' => $val5,
'key3' => $val6,
],
];
$result = [];
// Loop over each element of your input array
foreach ($myArray as $el)
// Use the value of the last element of each child array as the index to the child.
$result[end($el)] = $el;
var_dump($result);
输出:
/*
array(2) {
[3]=>
array(3) {
["key1"]=>
int(1)
["key2"]=>
int(2)
["key3"]=>
int(3)
}
[6]=>
array(3) {
["key1"]=>
int(4)
["key2"]=>
int(5)
["key3"]=>
int(6)
}
}
*/