2014-11-14 72 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