Home > DeveloperSection > Forums > php array merge and convert to json
Manoj Bhatt
Manoj Bhatt

Total Post:153

Points:1079
Posted on    May-02-2013 3:35 AM

 PHP PHP 
Ratings:


 1 Reply(s)
 1700  View(s)
Rate this:
Hi Expert!

I have two arrays (below). Is it possible to convert them into json string?

Array
        (
            [0] => size
            [1] => color
        )
Array
        (
            [0] => L
            [1] => Black
        )
Output structure should be:

[
   {"name":"size","value":"L"},
   {"name":"color","value":"Black"}
]

Thanks!


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    May-02-2013 8:26 AM

Hi Manoj!

Yes! It is possible to convert them into json string. You can try as below

$array1 = array('size', 'color');
$array2 = array('L', 'Black');

$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
    $jsonArray[] = array('name' => $name, 'value' => $value);
}

echo $json = json_encode($jsonArray);
This gives you

[{"name":"size","value":"L"},{"name":"color","value":"Black"}]

I hope it resolve your problem!

Don't want to miss updates? Please click the below button!

Follow MindStick