문제

I'm trying to create new stdclass with several arrays inside, and then to convert it to json array, for example i have this arrays:

$my_arr = array (name=>myname1, adress=>myadd1, phone=>myphone1);
$my_arr2 = array (name=>myname2, adress=>myadd2, phone=>myphone2);

And i would like to merge them to STDClass, This is what i have try:

$foo = new stdClass();
$foo->item1 = array();

foreach ($my_arr as $key => $value) {
$foo->item1[$key] = $value;
}

print_r($foo);
echo json_encode($foo);

The problem here is that i'm using only with the first array, The Result should be:

"items":[
    [
        {
            "name":"myname1",
            "adress":"myadd1",
            "phone":"myphone1"
        },
        {
            "name":"myname2",
            "adress":"myadd2",
            "phone":"myphone2"
        },
        {
            "name":"myname3",
            "adress":"myadd3",
            "phone":"myphone3"
        }
    ]
],

Thank you very much!

도움이 되었습니까?

해결책

You don't need to use stdClass, just array will work well.

$foo = array('items' => array($my_arr, $my_arr2));
echo json_encode($foo);

Of course you could use stdClass also:

$foo = new stdClass();
$foo->items = array($my_arr, $my_arr2);
echo json_encode($foo);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top