Pat
Pat

Reputation: 163

how to merge two arrays together and use json_encode

I have the following php code,

<?php
$first = array(1,2,3);
$last = array(4,5,6);
$k = 10;

echo json_encode(array('id' =>$k, 'name' => array( 'first' => $first, 'last' => $last)));
?>

I only get this result

{"id":10,"name":{"first":[1,2,3],"last":[4,5,6]}} 

but I want the following format, so that I can access the data in javascript like name.first and name.last

{"id":10,"name":[{"first":1,"last":4},{"first":2,"last":5},{"first":3,"last":6}] } 

can anyone help me out?

Thanks,

Pat

Upvotes: 3

Views: 1273

Answers (2)

Fallen
Fallen

Reputation: 4565

Sample code for a brute force solution for this:

$first = array(1,2,3);
$last  = array(4,5,6);
$name  = array();
for( $i = 0; $i < count($first); $i++) {
    $name[$i]['first'] = $first[$i];
    $name[$i]['last']  = $last[$i];
}
echo json_encode(array('id' =>$k, 'name' =>$name));

Upvotes: 0

bwoebi
bwoebi

Reputation: 23777

Use array_map to operate in the same time on the multiple arrays:

$array = array_map(function ($first, $last) { return array("first" => $first, "last" => $last); }, $first, $last);
echo json_encode(array('id' =>$k, 'name' => $array));

Upvotes: 4

Related Questions