2014-11-14 73 views
0

我使用json_decode來解析JSON文件。在for循環中,我試圖捕獲存在一個或另一個元素的JSON中的特定情況。我已經實現了一個似乎符合我需求的函數,但是我發現我需要使用兩個for循環來獲取它以捕獲我的兩個案例。確保訂單循環涉及json_decode()

我寧願使用一個循環,如果可能的話,但我堅持如何在一次傳遞中捕獲這兩種情況。下面是我想結果看起來像什麼樣機:

<?php 
function extract($thisfile){ 
    $test = implode("", file($thisfile)); 
    $obj = json_decode($test, true); 

    for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) { 
     //this is sometimes found 2nd 
     if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring1") { 
     } 

     //this is sometimes found 1st 
     if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring2") { 
     } 
    }  
} 
?> 

誰能告訴我,我怎麼能抓到一個迭代中上述兩種情況? 我顯然不能這樣做

if ($obj['patcher']['boxes'][$i]['box']['name'] == "string1" && $obj['patcher']['boxes'][$i]['box']['name'] == "string2") {} 

...因爲這條件永遠不會得到滿足。

+0

但你*使用*僅單迴路/傳...另外,'file' /'implode'是不必要的:只需使用'file_get_contents'。 – Jon 2014-11-14 23:18:23

+0

我只在示例中使用了單個傳遞來說明我希望結果如何。 – jml 2014-11-14 23:18:51

+0

你寫的是什麼,不行? – Aesphere 2014-11-14 23:27:04

回答

0

我發現,像什麼@喬恩曾提到可能是攻擊這個問題的最好辦法,至少對我來說:

<?php 
function extract($thisfile){ 
    $test = implode("", file($thisfile)); 
    $obj = json_decode($test, true); 
    $found1 = $found2 = false; 

    for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) { 
     //this is sometimes found 2nd 
     if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring1") { 
      $found1 = true; 
     } 

     //this is sometimes found 1st 
     if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring2") { 
      $found2 = true; 
     } 

     if ($found1 && $found2){ 
      break; 
     } 
    }  

} 
?> 
0

通常,當我的原始數據處於不理想的工作狀態時,我會做的是運行第一次循環傳遞以生成索引列表,以供我第二次傳遞。 所以從你的代碼一個簡單的例子:

<?php 
function extract($thisfile){ 
    $test = implode("", file($thisfile)); 
    $obj = json_decode($test, true); 

    $index_mystring2 = array(); //Your list of indexes for the second condition 

    //1st loop. 
    $box_name; 
    for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) { 
     $box_name = $obj['patcher']['boxes'][$i]['box']['name']; 

     if ($box_name == "mystring1") { 
      //Do your code here for condition 1 
     } 

     if ($box_name == "mystring2") { 
      //We push the index onto an array for a later loop. 
      array_push($index_mystring2, $i); 
     } 
    } 

    //2nd loop 
    for($j=0; $j<=sizeof($index_mystring2); $j++) { 
     //Your code here. do note that $obj['patcher']['boxes'][$j] 
     // will refer you to the data in your decoded json tree 
    } 
} 
?> 

誠然,你可以在更通用的方式做到這一點所以它的清潔劑(即產生第一和第二條件爲索引),但我認爲你的想法:)

+0

我想我正在尋找更符合@Jon所指的。 – jml 2014-11-15 02:18:24

+0

嗯...我不知道我跟着你想做什麼... – Aesphere 2014-11-15 02:39:55

+0

我想我缺乏信息。你是否在追蹤你發現的條件順序?比如說,你先找到mystring1,然後找到mystring2。然後基於這個結果,在mystring1之後的mystring2,你運行一段代碼。如果mystring2在mystring1之前被發現,你會運行一段不同的代碼? – Aesphere 2014-11-15 02:47:38