PHP json_decode [英] php json_decode
问题描述
在某些json代码(例如[{"a":"1"},{"a":"2"},{"a":"3"},{"b":"2"}]
)中进行测试,我想使用json解码,获取数据并做出判断,如果第一个a
nod是==
b
nod or fisrt a
点是!=
b
点.一些代码.
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++;
}
?>
现在我的结果是:
a11
a22
a33
我需要得到结果:
a11
b22
a33
推荐答案
如何比较不存在的数组字段?
How can you compare non-existing array fields?
没有$ num ['b']字段,有这些字段,其数组[4] (index 0..3)
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
在第一次迭代中将保持不变
$num
in first iteration will hold
array("a"=>1);
因此,如果您想与"b":2
进行比较,则必须使用以下模式:
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/zh/function. array-shift.php
Array_shift : http://php.net/manual/en/function.array-shift.php
这篇关于PHP json_decode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!