My problem may seem very simple, and I'm probably missing something. I need to save 2 fields from an array called $data1
as a different array.
[cat_id] => 1
[parent_id] => 0
[cat_left] => 1
[options] => 0
[name] => soccer
[creator] => 0
and I need to save cat_id => name
, like :
1 => soccer
I tried with foreach but all I managed to do is mess up more.
foreach($data1 as $k=>$v)
{
$cat_arr[]= $v['cat_id'] => $v['name'];
}
Any help would be appreciated.
I assume, that $data1
holds multiple sub-arrays of the form you posted. Then you can just use code like this:
$cat_arr = array();
foreach($data1 as $k=>$v) {
$cat_arr[ $v['cat_id'] ]= $v['name'];
}
You can use array_map()
, which is more elegant:
$data2 = array_map(
function ($n) {
return array($n['cat_id'] => $n['name']);
},
$data1
);