简体   繁体   中英

How do I extract multiple JSON objects from and array with PHP?

i've been trying to figure out how to extract multiple JSON objects from a json array.

I used this code from other post

$json = '[
            {"user_id":"1",
            "user_name":"Sayeed Amin",
            "time":"2019-11-06 13:21:26"}
        ]';

$someArray = json_decode($json, true);

foreach ($someArray as $key => $value) {
    echo $value["user_id"] . ", " . $value["user_name"] . ", " . $value["time"] . "<br>";
}

I can use this for a single json object inside an array, the result is good.

RESULT: 1, Sayeed Amin, 2019-11-06 13:21:26

How about if i have multiple json objects inside and array? like

$json = '[
        {"name":"Name",
        "value":"me you",
        "id":0,
        "type":"name",
        "first":"me",
        "middle":"",
        "last":"you"
        },
        {"name":"Email",
        "value":"myemail@gmail.com",
        "id":1,
        "type":"email"
        },
        {"name":"Phone",
        "value":"+12015550000",
        "id":2,"type":"phone"
        },
        {"name":"Address",
        "value":"my address\nsomecity, somestate\nsomepost\nUS",
        "id":3,
        "type":"address",
        "address1":"my address",
        "address2":"",
        "city":"somecity",
        "state":"somestate",
        "postal":"somepost",
        "country":"US"
        }
]';

$someArray = json_decode($json, true);

foreach ($someArray as $key => $value) {
    echo $value["name"] . ", " . $value["value"] . "<br>";
}

RESULT: Name, me you
Email, myemail@gmail.com
Phone, +12015550000
Address, my address somecity, somestate somepost US

DESIRED RESULT: Name, me you

If you only want to output the First Occurance of the array of objects then address the array appropriately like

$json = '[
        {"name":"Name",
        "value":"me you",
        "id":0,
        "type":"name",
        "first":"me",
        "middle":"",
        "last":"you"
        },
        {"name":"Email",
        "value":"myemail@gmail.com",
        "id":1,
        "type":"email"
        },
        {"name":"Phone",
        "value":"+12015550000",
        "id":2,"type":"phone"
        },
        {"name":"Address",
        "value":"my address\nsomecity, somestate\nsomepost\nUS",
        "id":3,
        "type":"address",
        "address1":"my address",
        "address2":"",
        "city":"somecity",
        "state":"somestate",
        "postal":"somepost",
        "country":"US"
        }
]';

$arr = json_decode($json);

echo $arr[0]->name . ", " . $arr[0]->value . "\n";

RESULT

Name, me you

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