第一个值作为PHP数组中的键 [英] First value as the key in PHP array
本文介绍了第一个值作为PHP数组中的键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个数组:
$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' ),
);
我想要这个输出:
$arr = array(
1 => array( 'animal' => 'dog', 'color' => 'red' ),
12 => array( 'animal' => 'cat', 'color' => 'green' ),
37 => array( 'animal' => 'lion', 'color' => 'blue' ),
);
有什么好主意,而不是使用php循环等?
有什么功能吗?像array_values
或array_combine
Any good idea instead of using php loops, etc ?
Any functions? like array_values
or array_combine
=================
可能的解决方案
=================
Possible solution
$new = array();
foreach( $arr as $item ){
$id = array_shift( $item );
$new[$id] = $item;
}
推荐答案
需要PHP> = 5.5.0,并且id
仍将位于嵌套数组中:
Requires PHP >= 5.5.0 and the id
will still be in the nested arrays:
$result = array_column($arr, null, 'id');
这篇关于第一个值作为PHP数组中的键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文