2013-09-22 52 views
0

我在24小时的黑客马拉松试图解决这个问题,所以请原谅它是否有点匆忙。在另一个foreach json循环中循环一次foreach json循环

1 for each循环工作得很好,我是从这个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; 
?> 

}?> 
+0

有一些错字错误,请首先纠正他们 –

+0

'$ 1 = 0;'? PHP变量不能以数字开头。 –

+0

固定问题... – user2320607

回答

2

这将创建一个$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 ... 
} 
0

的经验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; ?>