PHP ARRAY MERGE AND CONVERT TO JSON

Manoj Bhatt

Total Post:154

Points:1086
Posted by  Manoj Bhatt
PHP 
PHP
 2104  View(s)
Ratings:
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!
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: php array merge and convert to json

    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!

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!