循环数组时,该值变为空白

时间:2017-05-09 10:00:09

标签: php arrays for-loop

我从API获取数据和这样的结构

[
    {keyword: ["123","456","789"] , name :"hello" },
    {keyword: ["abc","def","ghi"] , name :"bye" },
    {keyword: ["987","654","321"] , name :"hello" }
]

我解码它并使用for循环来处理数据

for($i = 0, $l = count($result); $i < $l; ++$i) {
  echo join(',' , $result[0]->keyword);
}

我得到了

 ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

我尝试在循环中转储数组,结果是

array(3) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(3) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(3) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" } array(3) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" } array(3) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(3) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(3) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(3) { [0]=> string(0) "" [1]=> string(0) "" [2]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" } array(2) { [0]=> string(0) "" [1]=> string(0) "" }

但我可以使用循环中的数据

echo join(',' , $result[0]->keyword);
//123,456,789
var_dump($result[0]->keyword);
//array(3) { [0]=> string(6) "XXXXXXX" [1]=> string(9) "XXXXXXXX" [2]=> string(12) "XXXXXXXXXX" } 

数据中的所有其他数据都可以使用且没有编码问题,为什么只有这个数组的内容为空?

2 个答案:

答案 0 :(得分:0)

您可以在此处使用foreach循环来获得所需的结果。试试这个:

score.getName()

注意:大多数人会使用implodejoin只是内爆的别名。可以在你的代码中使用它。

答案 1 :(得分:0)

检查此代码,可能会解决您的问题

<?php
  $str = '[{"keyword": ["123","456","789"] , "name" :"hello" },
    {"keyword": ["abc","def","ghi"] , "name" :"bye" },
    {"keyword": ["987","654","321"] , "name" :"hello" }]';
  $obj = json_decode($str);
  foreach($obj as $elem){
      echo implode(",",$elem->keyword)."\n";
  }
?>

现场演示:https://eval.in/790394