2

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);
6
  • In your loop write $step1[] = $val; instead of $step1[$key] = $val; Commented Apr 19, 2018 at 5:42
  • 2
    you need to use array_push() Commented Apr 19, 2018 at 5:46
  • Let me know that all four input array will be always same length or can be changed? Commented Apr 19, 2018 at 5:48
  • 1
    All the array has same element everytime or each has different? Commented Apr 19, 2018 at 5:52
  • Array push is not helping me to get the desired result sir @BarclickFloresVelasquez Commented Apr 19, 2018 at 6:11

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.