猿问

使用php从json中的嵌套数组获取数据

我有来自 url feed 的 json。下面是一个示例。我没有正确执行 foreach 循环是问题所在


{

    "useLive": true,

    "models": [

        {

            "snapshotUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",

            "widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu7/previews/1537971705/5293074",

            "id": 5293074,

            "country": "",

            "gender": "female",

            "isNew": false,

            "previewUrl": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-full",

            "previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-big",

            "previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/b/a/a/baa515a42e75d80b0dc1e7a75bf4ea0f-thumb-small",

            "broadcastGender": "female",

            "snapshotServer": "eu7",

            "tags": ["autoTagPopular","keyword","keyword2"],

            "topBestPlace": 0,

            "username": "model1",

            "languages": ["en"],

            "stripScore": 998.5,

            "token": "93021860dbebd5ba27e604f6b4b93754"

        },

        {

            "snapshotUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",

            "widgetPreviewUrl": "https://img-eu.whatevercdn.com/eu8/previews/1537971700/6492104",

            "id": 6492104,

            "country": "",

            "gender": "female",

            "isNew": false,

            "previewUrl": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-full",

            "previewUrlThumbBig": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-big",

            "previewUrlThumbSmall": "https://st.whatevercdn.com/cdn/previews/2/b/3/2b366955f5a66d73ee038d43bf77c99b-thumb-small",

        }

    ],


我只收到第一个用户名,然后收到错误消息。


警告:/whatever 中的非法字符串偏移量“用户名”


有人能帮忙吗?


繁华开满天机
浏览 135回答 1
1回答

忽然笑

您应该在 foreach 中使用 $performers['models'] 数组,然后获取用户名它将正常工作尝试以下代码$performers = json_decode($data, true);&nbsp;if(isset($performers['models'])){&nbsp; &nbsp;&nbsp; &nbsp; foreach ($performers['models'] as $performer) {&nbsp; &nbsp; &nbsp; &nbsp; $info = (isset($performer["username"])) ? $performer["username"] : '';&nbsp; &nbsp; &nbsp; &nbsp; echo $info;&nbsp; &nbsp; &nbsp; &nbsp; echo "<br>";&nbsp; &nbsp; }&nbsp; &nbsp;}输出model1model2
随时随地看视频慕课网APP
我要回答