What i get.

This is the array which i get in my form post form multiple check boxes.

$test1 = array(
    '0' => 'test1',
    '1' => 'test2',
    '2' => 'test3'  
);


$test2 = array(
    '0' => 'test21',
    '1' => 'test22',
    '2' => 'test23' 
);


$test3 = array(
    '0' => 'test31',
    '1' => 'test32',
    '2' => 'test33' 
);


$test4 = array(
    '0' => 'test41',
    '1' => 'test42',
    '2' => 'test43' 
);

I need to convert this array in to something like this:

Result needed.

$result_needed = [ 

    '0' => ['0' => 'test1', '1' => 'test21', '2' => 'test31', '3' => 'test41'],
    '1' => ['0' => 'test2', '1' => 'test22', '2' => 'test32', '3' => 'test42'],
AND SO ON....
];

What i have tried so far?

I have tried to add this each array in to final array and then used foreach loop on it it get the result but it didn't help. Here is what i tried.

$final = ['test1' => $test1, 'test2' => $test2, 'test3' => $test3, 'test4' => $test4];


echo "<pre>";

$step1 = array();

foreach($final as $key => $val){

    $step1[$key] = $val;    

}

print_r($step1);
  • In your loop write $step1[] = $val; instead of $step1[$key] = $val; – B. Desai yesterday
  • 2
    you need to use array_push() – Barclick Flores Velasquez yesterday
  • Let me know that all four input array will be always same length or can be changed? – Alive to Die yesterday
  • 1
    All the array has same element everytime or each has different? – Gaurang Ghinaiya yesterday
  • Array push is not helping me to get the desired result sir @BarclickFloresVelasquez – always-a-learner yesterday
up vote 5 down vote accepted

You can do it with loops and pushing to result array

$final = ['test1' => $test1, 'test2' => $test2, 'test3' => $test3, 'test4' => $test4];

$step1 = [];
foreach ($final as $tests) {
    foreach ($tests as $key => $value) {
        if (!array_key_exists($key, $step1)) {
            $step1[$key] = [];
        }

        $step1[$key][] = $value;
    }
}

print_r($step1);

If all the array has same length and all are index array.

$result = array();

foreach($test1 as $key=> $test){
    $result[] = [$test1[$key],$test2[$key],$test3[$key],$test4[$key]];
}

print_r($result);

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.