Harikris Harikris - 26 days ago 7
JSON Question

How to pass multidimensional values to a json array?

I am trying to pass the value to an api through json request.

$payload = json_encode( array("phones"=> "971xxxxxxx",
"emails"=> "fadfad@xyz.com",
"id"=> "1"
) );


How will i pass the below multi dimensional values to a json request like the above code?

{ "contactList": [ { "phones" : ["+91 9000000034"], "emails" : [fadfad@xyz.com], "id" : 1 }, { "phones" : ["+91 903-310-00-001"], "emails" : [krs@xyz.in], "id" : 2 } ] }

Answer

Store the data as nested / multidimensional arrays before passing it to json_encode.

$array = array();
$array["contactList"] = array(
array(  "phones"=> "971xxxxxxx",
        "emails"=> "fadfad@xyz.com",
        "id"=> "1"
    ),
array(  "phones"=> "+91 903-310-00-001",
        "emails"=> "krs@xyz.in",
        "id"=> "2"
    )
);     

$payload = json_encode($array);

echo $payload;

produces

{"contactList":[{"phones":"971xxxxxxx","emails":"fadfad@xyz.com","id":"1"},{"phones":"+91 903-310-00-001","emails":"krs@xyz.in","id":"2"}]}

If you need to hold values like the phone numbers inside an array, simply wrap them in an array.

Comments