Test in some json code, like [{"a":"1"},{"a":"2"},{"a":"3"},{"b":"2"}], I want use json decode, get the data and make a judge, if first a nod is == b nod or fisrt a nod is != b nod. some code here.
<?php
header("Content-type: text/html; charset=utf-8");
$json = json_decode('[{"a":"1"},{"a":"2"},{"a":"3"},{"b":"2"}]',true);
$number=1;
foreach($json as $num){
if($num['a']!=$num['b']){
if($num['a']){
echo 'a'.$number.''.$num['a'].'<br />';
}
}else{
if($num['a']){
echo 'b'.$number.''.$num['a'].'<br />';
}
}
$number++;
}
?>
Now my result is:
a11
a22
a33
And I need get the result:
a11
b22
a33
2 Answers 2
How can you compare non-existing array fields?
there is no $num['b'] field, there are these fields, its array[4] (index 0..3)
- a:1
- a:2
- a:3
- b:2
$num in first iteration will hold
array("a"=>1);
so if you wanna compare to "b":2 you have to use this pattern:
$cmpr = array_shift($json);
...
if($num != $cmpr)
Array_shift : http://php.net/manual/en/function.array-shift.php
2 Comments
You're trying to refer to the b variable when b is not currently defined. you must first loop through and find the b variable. http://codepad.org/0SnrPp6N
<?php
$json = json_decode('[{"a":"1"},{"a":"2"},{"a":"3"},{"b":"2"}]',true);
foreach ($json as $var) {
if (isset($var['b'])) { $b = $var['b']; break; }
}
$i=0;
foreach ($json as $var) {
if (!isset($var['a']))
continue;
if ($var['a']!=$b)
echo "a".++$i."$var[a]\n";
else
echo "b".++$i."$var[a]\n";
}
$num['a']and make out which$num['a']is equal to$num['b']such asa11,b22,a33