简体   繁体   English

PHP - 在没有“字符串”的情况下循环遍历 JSON 数组?

[英]PHP - Looping through JSON Array without "string"?

So I have question.所以我有疑问。 I have an JSON Array我有一个 JSON 数组

Here's the JSON: http://pastebin.com/raw/XEzAEdfg这是 JSON: http : //pastebin.com/raw/XEzAEdfg

How could I loop it through?我怎么能循环它? Here's what I've tried at the moment:这是我目前尝试过的:

$output = json_decode($result2);
foreach($output as $SuiFag){
    echo $SuiFag->aaData[6];
}
?>

I suppose you data json data should be an object attribute named "aaData" of type array so only a [ character should be there, and { and } should define the start and the end of the json object(traling comma is not allowed):我想你的数据json数据应该是一个名为“aaData”的数组类型的对象属性,所以只有一个 [ 字符应该在那里,而 { 和 } 应该定义json对象的开始和结束(不允许使用逗号):

$result2='{
   "aaData": [
         "Knife",
         "/id/1676/",
         "★ Karambit | Stained (Field-Tested)<\/a>",
         "234.87",
         "224.85",
         "5907380460<\/a>",
         "0.2123493403<\/a>",
         "Inspect<\/a>"
      ]
}';

So you can use direct object attribute access (you need foreach to scan an array but not the attribute of an object):因此,您可以使用直接对象属性访问(您需要 foreach 来扫描数组而不是对象的属性):

$output = json_decode($result2);
echo $output->aaData[6];

OR if your json structure is something like this: allowed):或者,如果您的 json 结构是这样的:允许):

$result2='{
    ...
   "aaData": [
        [
         "Knife",
         "/id/1676/",
         "★ Karambit | Stained (Field-Tested)<\/a>",
         "234.87",
         "224.85",
         "5907380460<\/a>",
         "0.2123493403<\/a>",
         "Inspect<\/a>"
        ],
        ...
    ]
}';

then your code should be:那么你的代码应该是:

$output = json_decode($result2);
foreach($output->aaData as $SuiFag){
    echo $SuiFag[6];
}

TO print every 6th element of every element of the array "aaData";打印数组“aaData”的每个元素的每第 6 个元素;

You need to loop through the aaData array then output the 6th line.您需要遍历 aaData 数组,然后输出第 6 行。 The below will output the 6th line of every aaData array下面将输出每个 aaData 数组的第 6 行

$output = json_decode($result2);
foreach($output as $SuiFag) {
    for($i=0; $i<count($SuiFag);$i++) {
        echo $SuiFag[$i][6] . '<br>';
    }
}
?>

Of course you can add a third loop if you want to echo each item of the array out当然,如果您想将数组的每个项目回显出来,您可以添加第三个循环

$output = json_decode($result2);
foreach($output as $SuiFag) {
    for($i=0; $i<count($SuiFag);$i++) {
        for($x=0; $x<count($SuiFag[$i]);$x++) {
            echo $SuiFag[$i][$x] . '<br>';
        }
    }
}
?>

Since you have only the aaData in your json you could shorten this down to but above allows for further items in your json array:由于您的 json 中只有 aaData,您可以将其缩短为但上面允许您的 json 数组中的更多项目:

foreach($output->aaData as $SuiFag) {
    for($i=0; $i<count($SuiFag);$i++) {
        echo $SuiFag[$i] . '<br>';
    }
}

Credits to lamp76归功于 lamp76

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM