php - Ensure order in for loop involving json_decode() -
i'm using json_decode
parse json files. in loop, attempt capture specific cases in json in 1 element or exist. i've implemented function seems fit needs, find need use 2 loops catch both of cases.
i rather use single loop, if that's possible, i'm stuck on how both cases caught in single pass. here's mockup of result like:
<?php function extract($thisfile){ $test = implode("", file($thisfile)); $obj = json_decode($test, true); ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) { //this found 2nd if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring1") { } //this found 1st if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring2") { } } } ?>
can tell me how catch both cases outlined above within single iteration? not
if ($obj['patcher']['boxes'][$i]['box']['name'] == "string1" && $obj['patcher']['boxes'][$i]['box']['name'] == "string2") {}
...because condition never met.
generally when have raw data in order isn't ideal work run first loop pass generate a list of indexes me pass through second time. quick example code:
<?php function extract($thisfile){ $test = implode("", file($thisfile)); $obj = json_decode($test, true); $index_mystring2 = array(); //your list of indexes second condition //1st loop. $box_name; ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) { $box_name = $obj['patcher']['boxes'][$i]['box']['name']; if ( $box_name == "mystring1") { //do code here condition 1 } if ($box_name == "mystring2") { //we push index onto array later loop. array_push($index_mystring2, $i); } } //2nd loop for($j=0; $j<=sizeof($index_mystring2); $j++) { //your code here. note $obj['patcher']['boxes'][$j] // refer data in decoded json tree } } ?>
granted can in more generic ways it's cleaner (ie, generate both first , second conditions indexes) think idea :)
Comments
Post a Comment