[英]PHP: how to create associative array by key?
I have simple array 我有简单的数组
array(
array( 'id'=>5, 'something' => 2, 'dsadsa' => 'fsfsd )
array( 'id'=>20, 'something' => 2, 'dsadsa' => 'fsfsd )
array( 'id'=>30, 'something' => 2, 'dsadsa' => 'fsfsd )
)
How to create associative array by id field (or something else) from it in the right way? 如何通过id字段(或其他东西)以正确的方式创建关联数组?
array(
'5' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
'20' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
'30' => array( 'something' => 2, 'dsadsa' => 'fsfsd )
)
Something along these lines. 沿着这些方向的东西。
$new_array = array();
foreach ($original_array as &$slice)
{
$id = (string) $slice['id'];
unset($slice['id']);
$new_array[$id] = $slice;
}
@NikitaKuhta, nope. @NikitaKuhta,不。 There is no slice function which returns a column of values in a 2D keyed table associated with a given key or column heading.
没有切片函数返回与给定键或列标题关联的2D键控表中的值列。 You can use some of the callback array_... functions, but you will still need to execute a custom function per element so its just not worth it.
你可以使用一些回调数组_...函数,但你仍然需要为每个元素执行一个自定义函数,所以它不值得。 I don't like Core Xii's solution as this corrupts the original array as a side effect.
我不喜欢Core Xii的解决方案,因为这会破坏原始阵列的副作用。 I suggest that you don't use references here:
我建议你不要在这里使用引用:
$new_array = array();
foreach ($original_array as $slice) {
$id = (string) $slice['id'];
unset($slice['id']);
$new_array[$id] = $slice;
}
# And now you don't need the missing unset( $slice)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.