How can I combine two arrays for names and values to align side by side in php

Viewed 136

I have two arrays which I wish to combine so that name and value can be side by side.

I have this code:

 $mgl = array(
         '200101', 
         '200201', 
         '200202'
         );
    $mpro = array(
           'Current Account',
           'Regular Saving Account', 
           'Ileya Target' 
           );

      array_push($response, array(
                "glno"=>$mgl, 
                 "product"=>$mpro

                 ));

echo json_encode(array("server_response"=> $response));

When I viewed it it appeared this way:

{"server_response":[{"glno":["200101","200201","200202"],"product":["Current Account","Regular Saving Account","Ileya Target"]}]}

I want it in this format

{"server_response":[
 {"glno":"104100","product":"Micro Loans"}, 
 {"glno":"200101","product":"Current Account"}, 
 {"glno":"200201","product":"Regular Saving Account"}
]}
2 Answers

It's easy enough using a foreach loop, using the first array as the start point and (as long as the arrays are the same length) just pick out the same value from the second array...

$response = [];
foreach ( $mgl as $key => $value )  {
    $response[] = ["glno" => $value, "product" => $mpro[$key]];
}

echo json_encode(array("server_response"=> $response));

gives..

{"server_response":[{"glno":"200101","product":"Current Account"},
    {"glno":"200201","product":"Regular Saving Account"},
    {"glno":"200202","product":"Ileya Target"}]}

You could use array_combine(), this would be one solution of many in PHP.

<?php
$mgl=array("Micro Loans","Current Account","Ileya Target");
$mpro=array("104100","200101","200201");
$c=array_combine($mgl,$mpro);
print_r($c);
?>
Related