I think this has been up before, but could\'nt find any answer to it. If it\'s already answered please point me in the right direction with a link.
I have an array t
Check this out this is what expected result
<?php
$arrData = array(
"5" => array
(
"8" => "Vit"
),
"6" => array
(
"7" => "Guld"
)
);
foreach($arrData as $key=>$value):
foreach($value as $k=>$v):
$data[$k] = implode(',',$arrData[$key]);
endforeach;
endforeach;
print_r($data);
?>
The problem here is preserving the keys for the identifier you want. You have some names strings that have the same key (like Blå and Röd). You either need to store these in an array or be willing to lose the key.
Example with php5.3:
$processed = array_map(function($a) { return array_pop($a); }, $arr);
This will give you:
[0] => Röd
[1] => Blå
[2] => Bobo
[3] => Grön
[4] => Sten
[5] => Vit
[6] => Guld
[7] => Lyxig
It has become clear the keys on the inner array need to be preserved because they are some kind of id. With that said you must change the end structure you're going for because you can have 2 of the same key in a single array. The simplest structure then becomes:
[8] => Array
(
[0] => Röd,
[1] => Blå,
[2] => Vit,
[3] => Grön
)
[6] => Array
(
[0] => Bobo,
[1] => Lyxig
)
[7] => Array
(
[0] => Sten,
[1] => Guld
)
To get this structure a simple loop will work:
$processed = array();
foreach($arr as $subarr) {
foreach($subarr as $id => $value) {
if(!isset($processed[$id])) {
$processed[$id] = array();
}
$processed[$id][] = $value;
}
}
PHP array_column
$new_array = array_column($old_array,0);
This will retrieve the value at index 0 for each array within $old_array. Can also be using with associative arrays.
use :
public function remove_level($array) {
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, $value);
}
}
return $result;
}
which will return second level array values in the same order of the original array. or you can use array_walk
$results = array();
array_walk($array, function($v, $k) use($key, &$val){
array_merge($results, $v);
});
Below code will also achieve the same result.
$resultArray = array_map('current',$inputArray);
OR
$resultArray = array_map('array_pop',$inputArray);
Note: I have ignored OP's expected result keys. Because it is not possible to have the same keys in the array. The last key will replace the previous one if the same.
foreach($array as $key=>$val) {
$newarr[$val] = $array[$key][$val];
}
untested!