【问题标题】:Parsing json key value in PHP (multidimensional array)PHP中解析json键值(多维数组)
【发布时间】:2017-01-14 17:07:30
【问题描述】:

到目前为止,我想我已经“尝试”了几乎所有建议的方法来解析来自 POST 响应的一个或多个键的值。我已经能够将其简化一点,但我非常感谢有人愿意提供的任何帮助。我的目标是检索“id”和“campaign_id”键的值(或任何其他键值)。不用说我是初学者^_^

我们来了..

$contents = ($this->response);
$enc = ($contents);

结果:

Array ( [0] => [ { "url": "http://www.aguabenito.com", "name": "Bikinis - New arrivals", "prefix": "AGUA", "notes": "", "updated_at": "2017-01-14 16:26:35", "created_at": "2017-01-14 16:26:35", "id": 4609 }, [], [ { "id": 3531, "url_code": "R0uvzO", "alias": null, "campaign_id": 4609, "paidchannel_id": 104, "deleted_at": null, "created_at": "2017-01-14 16:26:35", "updated_at": "2017-01-14 16:26:35" } ] ] ) 

然后..

for ($i = 0; $i < count($enc); ++$i) {
    print $enc[$i];
}

结果:

[
    {
        "url": "http://www.aguabenito.com",
        "name": "Bikinis - New arrivals",
        "prefix": "AGUA",
        "notes": "",
        "updated_at": "2017-01-14 16:26:35",
        "created_at": "2017-01-14 16:26:35",
        "id": 4609
    },
    [],
    [
        {
            "id": 3531,
            "url_code": "R0uvzO",
            "alias": null,
            "campaign_id": 4609,
            "paidchannel_id": 104,
            "deleted_at": null,
            "created_at": "2017-01-14 16:26:35",
            "updated_at": "2017-01-14 16:26:35"
        }
    ]

我不敢说我​​只是从这里开始绕圈子。当我尝试获取任何值时,我不断收到非法字符串偏移或未定义索引错误。真的希望了解我做错了什么以及我应该如何检索这些键中的一个或多个的值。

希望在以下方面有所作为:

$campaign_id = '4609';
$first_urlcode = 'R0uvzO';
$first_urlcode_id = '3531';
$second_urlcode = 'abc123';
$second_urlcode_id = '1234';

【问题讨论】:

  • 为什么不以json_decode()开头?
  • @EatPeanutButter, $enc = json_decode($contents);给出错误 json_decode() 期望参数 1 是字符串,给定数组
  • json_decode($contents[0])
  • 感谢@EatPeanutButter,但随后因为Object of class stdClass could not be converted to string而失败
  • 啊,虽然$enc = json_decode($contents[0], true); 的真正参数有所帮助

标签: php arrays json parsing multidimensional-array


【解决方案1】:

感谢@EatPienutButter 帮助我!!

这让我再次直走)))))

$enc = json_decode($contents[0], true);

$campaignid = ($enc[0]['id']);
$first_urlcode = ($enc[2][0]['url_code']);
$first_urlcode_id = ($enc[2][0]['id']);

【讨论】:

    猜你喜欢
    • 2013-04-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-18
    • 2011-01-30
    相关资源
    最近更新 更多