无法从数组中获取元素

时间:2017-09-22 04:08:17

标签: php arrays json list

我正在尝试获取制造商字段的值列表,但除了白屏外没有任何其他内容,没有错误,一切似乎都是正确的,但没有任何作用

<?php

function removeBomUtf8($s){
  if(substr($s,0,3)==chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF'))){
        return substr($s,3);
    }else{
        return $s;
    }
}

$url = "http://www.pureexample.com/backend/data/car-sale.json";
$content = file_get_contents($url);
$clean_content = removeBomUtf8($content);
$decoded = json_decode($clean_content);

while ($el_name = current($decoded)) {
    if ($el_name == 'Manufacturer') {
        echo key($decoded).'<br />';
    }
    next($decoded);
}
?>

3 个答案:

答案 0 :(得分:0)

$decoded数组中的每个条目都应该是stdclass对象表示的类似

{
    "Manufacturer": "Toyota",
    "Sold": 1200,
    "Month": "2012-11"
}

从你的评论中得出......

  

我希望看到所有与制造商相关的行如1&#34;制造商&#34;:&#34;丰田&#34;,2&#34;制造商&#34;:&#34;&#34;福特&#34; 3&#34;制造商&#34;:&#34;宝马&#34;等

你可能会追求的是

$manufacturers = array_map(function($el) {
  return sprintf('"Manufacturer": "%s"', $el->Manufacturer);
}, $decoded);
echo '<ol><li>', implode('</li><li>', $manufacturers), '</li></ol>';

演示〜https://eval.in/866131

或者,只需使用$decoded ...

循环foreach
?>
<ol>
  <?php foreach ($decoded as $el) : ?>
  <li>"Manufacturer": "<?= htmlspecialchars($el->Manufacturer) ?>"</li>
  <?php endforeach ?>
</ol>

答案 1 :(得分:0)

$decoded是一个对象数组(类型为StdClass):当您调用current时,您将返回具有三个属性的对象:Manufacturer,Sold和Month。如果您只想打印出制造商名称,请按如下方式编辑代码:

while ($el_name = current($decoded)) {
  echo $el_name->Manufacturer . '<br>';
  next($decoded);
}

然而,正如其中一位评论者提到的那样,当前/下一个语法非常模糊,并不容易理解。你最好不要写作:

foreach($decoded as $el_name) {
  echo $el_name->Manufacturer . '<br>';
}

答案 2 :(得分:0)

您正在处理一个对象,为了使其更简单,请尝试运行此对象以获得您想要的结果:

<?php

function removeBomUtf8($s){
  if(substr($s,0,3)==chr(hexdec('EF')).chr(hexdec('BB')).chr(hexdec('BF'))){
        return substr($s,3);
    }else{
        return $s;
    }
}

$url = "http://www.pureexample.com/backend/data/car-sale.json";
$content = file_get_contents($url);
$clean_content = removeBomUtf8($content);
$decoded = json_decode($clean_content);

foreach ($decoded as $car) {
echo "Manufacturer is: $car->Manufacturer" . "<BR>";
echo "Sold is: $car->Sold" . "<BR>";
echo "Month is: $car->Month" . "<BR>";
echo "<P>";
}
?>

以上是PHP代码的输出:

Manufacturer is: Toyota
Sold is: 1200
Month is: 2012-11

Manufacturer is: Ford
Sold is: 1100
Month is: 2012-11

Manufacturer is: BMW
Sold is: 900
Month is: 2012-11

Manufacturer is: Benz
Sold is: 600
Month is: 2012-11

Manufacturer is: GMC
Sold is: 500
Month is: 2012-11

Manufacturer is: HUMMER
Sold is: 120
Month is: 2012-11