简体   繁体   中英

How to add json_encode array into json_encode object?

How to add json_encode array into json_encode object ? or other way to make below result?

php result response to jquery ajax

{”a_obj”:”a_obj”,“b_obj_json”:[
        {“b_arr1”:b_arr1,“b_arr1-2”:“b_arr1-2”},
        {“b_arr2”:b_arr2,“b_arr2-2”:”b_arr2-2”},
        ... from db push
    ]
}

:

$response_array = array('a_array'=>'a_array');
$response_array_object = json_encode($response_array, JSON_FORCE_OBJECT);


$b_arr =array(
     'b_arr1'=>'b_arr1',
);
json_encode($b_arr);

$response_array_object->append($b_arr);

echo $response_array_object;

Convert JSON to Array with 'json_decode'
then use 'array_append' to add new data then 'json_encode' it again.

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
$array = (array) json_decode($json);

$append = array(
    'username' => array('alias' => 'somename', 'realname' => 'stacky');
    'password' => 'somepass';
);

$combined = array_merge($array, $append);
$encoded = json_encode($combined);

print_r($encoded);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM