我有这个数组
[InstrumentCategory] => Array
(
[0] => Array
(
[id] => 4
[title] => Training
[InstrumentsCategory] => Array
(
[id] => 56
[instrument_id] => 28
[category_id] => 4
)
)
[1] => Array
(
[id] => 8
[title] => Working time flexibility
[InstrumentsCategory] => Array
(
[id] => 57
[instrument_id] => 28
[category_id] => 8
)
)
[2] => Array
(
[id] => 16
[title] => Income support for workers
[InstrumentsCategory] => Array
(
[id] => 55
[instrument_id] => 28
[category_id] => 16
)
)
)
是否有其他方法来提取id=>值对(注意,在这种情况下,id
是子数组中的一个键)比for
循环?
Thanks in advance
如果您使用PHP 5.3,您可以使用以下代码(array_reduce):
$r = array_reduce($input_array,
function ($res, $cur) {
return $res + array($cur['id'] => $cur);
}, array());
之后,$r
包含id => value对。
Edit:使用PHP版本<5.3,你可以这样做:
function array_reduce_cb_id ($res, $cur) {
return $res + array($cur['id'] => $cur);
}
$r = array_reduce($input_array, 'array_reduce_cb_id', array());