在另一个 foreach json 循环中循环一个 foreach json 循环


Loop a foreach json loop in another foreach json loop

我正在参加一个 24 小时的黑客马拉松,试图解决这个问题,所以,如果它有点匆忙,请原谅。

每个循环的第一个工作正常,我从这个 url 中获取类别列表

https://dev.xola.com/api/categories

我用这个抓住清单

$fullurl = "https://dev.xola.com/api/categories"; 
$string .= file_get_contents($fullurl); // get json content
$json_a = json_decode($string, true); //json decoder

然后用这个循环它

<?
foreach($json_a as $v)
{?>
echo $v ?}>

现在,每次查看第二个,我想从此URL中获取项目

https://dev.xola.com/api/experiences

与上一个网址中的类别匹配

so samething 
$fullurl = "https://dev.xola.com/api/categories"; 
$string .= file_get_contents($fullurl); // get json content
$json_b = json_decode($string, true); //json decoder

这是我尝试过的完整循环

 <?
 $i=0;
foreach($json_a as $v)

$i++ {?> 回声$v?

 foreach($json_b as $x){?>
 if($v==$x):   
 echo $v
 endif;
 ?>
}?>

这将创建一个$result数组,其中仅包含早期获取类别的数据:

<?php
$categories_url = "https://dev.xola.com/api/categories";
$data = file_get_contents($categories_url);
$categories = json_decode($data, true);
$experiences_url = "https://dev.xola.com/api/experiences";
$data = file_get_contents($experiences_url);
$experiences = json_decode($data, true);
$result = array();
foreach ($experiences['data'] as $experience)
{
    if (in_array($experience['category'], $categories))
    {
        $result[] = $experience;
    }
}
print_r($result);

您可以通过以下方式轻松读取结果:

foreach ($result as $item)
{
    echo $item['category'], "'n";
    echo $item['desc'], "'n";
    //... other data available ...
}
体验 JSON

的数据结构与类别 JSON 不同,因此if($v==$x)永远不会匹配。如果您想从类别网址中查找某个类别的体验中的所有结果,可以执行以下操作:

<?
    $BASE_URL = 'https://dev.xola.com/api/';
    $categories = json_decode(file_get_contents($BASE_URL . 'categories'));
    $experiences = json_decode(file_get_contents($BASE_URL . 'experiences'));
    $matches = array();
    foreach( $categories as $category ) {
        foreach( $experiences->data as $experience ) {
            if( $experience->category === $category ) {
                $matches[] = $experience;
            }
        }
    }
?>
<? foreach( $matches as $match ) : ?>
    <? echo $match->category; ?><br>
<? endforeach; ?>