2013-09-22 53 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; ?>