Reputation: 33
I want to combine multiple arrays to make specific format.
$fieldArray=[];
$fieldArray['field_val']['key_1']=array('1');
$fieldArray['field_val']['key_2']=array('1','2','3','4');
$fieldArray['field_val']['key_3']=array('5','6','7','8');
$fieldArray['field_val']['key_4']=array('9','10','11','12');
$fieldArray['field_val']['key_5']=array('30');
Result Should be
1,1,5,9,30
1,2,6,10,30
...and so on
I have tried the following code. But it not give me the correct results.
echo '<pre>';
$i=0;
$newArray=[];
foreach($fieldArray['field_val'] as $key=>$values){
if($i==0){
$orderId=$values[0];
}
array_unshift($values,$orderId);
$newArray[]=$values;
$i++;
}
array_shift($newArray);
array_pop($newArray);
print_r($newArray);
I need the following output.
1,1,5,9,30
1,2,6,10,30 and so on
Upvotes: 3
Views: 86
Reputation: 18557
Once check the output of this, As I can see, you are kinda transposing array. I first transposed and wrote a snippet for your requirement.
$temp = array_map(null, ...$fieldArray['field_val']); // transposing array
foreach ($temp as $key => &$value) {
foreach ($value as $key1 => &$value1) {
// checking if empty
if(empty($value1)){
// fetching key1 value from first array and
// mapping it to empty values for all other arrays except first
$value1 = $temp[0][$key1];
}
}
}
echo implode("\n", array_map(function ($value) { // replace with br if web
return implode(",", $value);
}, $temp));
Note: Must have data from the initial index.
Explanation:
EDIT
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
$temp = transpose($fieldArray['field_val']); // transposing array
function flipDiagonally($arr) {
$out = array();
foreach ($arr as $key => $subarr) {
foreach ($subarr as $subkey => $subvalue) {
$out[$subkey][$key] = $subvalue;
}
}
return $out;
}
Upvotes: 2