【问题标题】:json_decode with array and objects带有数组和对象的 json_decode
【发布时间】:2015-02-26 18:23:08
【问题描述】:

我有 JSON,需要从中获取一些信息。

<?

$json = {"ship":{"shipname":"Harbinger Navy Issue","shipid":"33155","dna":"33155:3520;6:11561;1:19280;1:19278;1:4349;1:19191;1:2364;2:1248;3:2048;1:31372;3:2488;10:12814;6::"},"high":[{"Heavy Pulse Laser II:3520":6}],"medium":[{"Shield Boost Amplifier I:11561":1},{"Pith A-Type EM Ward Field:19280":1},{"Pith A-Type Thermic Dissipation Field:19278":1},{"Pithum C-Type Adaptive Invulnerability Field:4349":1},{"Pithum A-Type Medium Shield Booster:19191":1}],"low":[{"Heat Sink II:2364":2},{"Capacitor Flux Coil II:1248":3},{"Damage Control II:2048":1}],"rig":[{"Medium Capacitor Control Circuit I:31372":3}],"subsystem":[],"drones":[{"Warrior II:2488":10}],"charge":[{"Conflagration M:12814":6}]};

$obj_o = json_decode($json);
$test = $obj_o->ship->shipname;
$test2 = $obj_o->high->{0};
$test3 = $obj_o->ship->high->{0}->{0};
$test4 = $obj_O->ship->dna;
$test5 = $obj_a[high][1];
//$test6 = $obj_a[medium][1]{1};

$test6 = $result->ship->shipname;

echo 'test6:';
echo $test6;
echo '</br>';
echo 'test5:';
echo $test5;
echo '</br>';
echo $test;
echo '</br>';
echo 'test2:';
echo $test2;
echo '</br>';
echo 'test3:';
echo $test3;
echo '</br>';

?>

我想从 JSON 中选择“高”并将其分成 3 部分:

  1. 重脉冲激光 II
  2. 3520
  3. 6

我该怎么做?

【问题讨论】:

  • $json = {"ship":"foo"}; 既不是有效的 PHP 也不是有效的 JSON。请在此处发布之前提取一个最小示例。

标签: php arrays json object decode


【解决方案1】:

编辑:如果您希望它作为数组返回:

$obj_o = json_decode($json, true);
foreach($obj_o["high"] as $key => $value){
    $keyArray = explode(":", $key);
    //$keyArray[0] is 'High Pulse Laser II'
    //$keyArray[1] is 3520
    //$value is 6
}

如果你想要一个对象:

$obj_o = json_decode($json);
foreach($obj_o->high as $weapon) {
    foreach($weapon as $key => $value) {
        $keyArray = explode(":", $key);
        //$keyArray[0] is 'High Pulse Laser II'
        //$keyArray[1] is 3520
        //$value is 6   
    }
}

【讨论】:

  • 当我使用它时会出现致命错误:无法在第 95 行的 /var/customers/webs/ni7/Eve/Eft/display.php 和 json_decode($ json, true) $keyArray[0] as echo
  • @James Spence, json_decode 返回 stdClass 类型的对象,而不是 php 数组。如果要返回 php 数组,则需要添加 true 作为第二个参数,即 json_decode($myjson, true)
  • 当我 json_decode($json, true) 然后只能通过 echo bsp 来。回声 $keyArray[0];结果为 0 并且通过 echo $value;结果是:阵列不是我需要的(高脉冲激光 II),3520,6
  • 答案已更新。我只是按照你的方式运行你的代码。参见“如果你想要一个对象”。
  • 代码对我有很大帮助!谢谢谢谢谢谢只有一个问题我有那么高有2个阵列它如何与tihs一起工作?我用“中等”尝试过我的结果是`keyarray0:Pithum A-Type Medium Shield Booster keyarray1:19191 value:1`但是数组2无法显示
猜你喜欢
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2011-08-24
  • 1970-01-01
  • 2010-10-21
  • 2020-04-12
  • 1970-01-01
相关资源
最近更新 更多