I have this array:
我有这个数组:
$arr = array(
0 => array( 'id' => 1, 'animal' => 'dog', 'color' => 'red' ),
1 => array( 'id' => 12, 'animal' => 'cat', 'color' => 'green' ),
2 => array( 'id' => 37, 'animal' => 'lion', 'color' => 'blue' ),
);
and I want this output:
我想要这个输出:
$arr = array(
1 => array( 'animal' => 'dog', 'color' => 'red' ),
12 => array( 'animal' => 'cat', 'color' => 'green' ),
37 => array( 'animal' => 'lion', 'color' => 'blue' ),
);
Any good idea instead of using php loops, etc ?
Any functions? like array_values
or array_combine
任何好主意而不是使用PHP循环等?任何功能?比如array_values或array_combine
=================
Possible solution
=================可能的解决方案
$new = array();
foreach( $arr as $item ){
$id = array_shift( $item );
$new[$id] = $item;
}
2 个解决方案
#1
Requires PHP >= 5.5.0 and the id
will still be in the nested arrays:
需要PHP> = 5.5.0且id仍将在嵌套数组中:
$result = array_column($arr, null, 'id');
#2
One can define a new array and loop through the main array, using array_shift
to pop first element (the id field) and then make the remaining part, value for that index in new array:
可以定义一个新数组并循环遍历主数组,使用array_shift弹出第一个元素(id字段),然后在新数组中为该索引创建剩余部分值:
$new = array();
foreach( $arr as $item ){
$id = array_shift( $item );
$new[$id] = $item;
}
#1
Requires PHP >= 5.5.0 and the id
will still be in the nested arrays:
需要PHP> = 5.5.0且id仍将在嵌套数组中:
$result = array_column($arr, null, 'id');
#2
One can define a new array and loop through the main array, using array_shift
to pop first element (the id field) and then make the remaining part, value for that index in new array:
可以定义一个新数组并循环遍历主数组,使用array_shift弹出第一个元素(id字段),然后在新数组中为该索引创建剩余部分值:
$new = array();
foreach( $arr as $item ){
$id = array_shift( $item );
$new[$id] = $item;
}