我有一个json数组wherer我想通过使用for循环将json直到最后一个元素,因为我想获得json数组中的数组元素的数量,我在anarray中有超过3个对象,所以我很困惑如何解析json直到最后一个元素, 我可以说你的想法
Count($json);
echo count;
for(i=0;i<l=count($json);i++)
{
then print the value of each key
}
我被卡住了,因为我没有固定长度的json,因为它是服务器响应它可能会返回一个对象,可能是两次或三次或多次,所以我认为这样做会更好循环,作为一个json包含多个json与3个键,如国家可以有多个州,一个州可以有多个区,plaese帮助我,我被困在最近2天的问题 谢谢
答案 0 :(得分:1)
一个想法:
function printJson($json) {
foreach($json as $index=>$value) {
if(is_array($value)) {
printJson($value);
} else {
echo 'Value :'.$value.'<br />';
}
}
}
$stringJson = "{'location':[{...}]}"; //for example
printJson(json_decode($stringJson));
答案 1 :(得分:0)
您也可以使用json_decode()
解码json tring,这将为您提供一个php变量,然后您可以使用php轻松迭代它。
例如
$string = '{"image":"fox.png","puzzlepieces":{"f":{"puzzlepiece":"one","position":"top:121px;left:389px;"},"x":{"puzzlepiece":"three","position":"top:164px;left:455px;"},"o":{"puzzlepiece":"two","position":"top:52px;left:435px;"}}}';
var_dump(json_decode($string));
将输出为
object(stdClass)[1]
public 'image' => string 'fox.png' (length=7)
public 'puzzlepieces' =>
object(stdClass)[2]
public 'f' =>
object(stdClass)[3]
public 'puzzlepiece' => string 'one' (length=3)
public 'position' => string 'top:121px;left:389px;' (length=21)
public 'x' =>
object(stdClass)[4]
public 'puzzlepiece' => string 'three' (length=5)
public 'position' => string 'top:164px;left:455px;' (length=21)
public 'o' =>
object(stdClass)[5]
public 'puzzlepiece' => string 'two' (length=3)
public 'position' => string 'top:52px;left:435px;' (length=20)
我的xdebug扩展在WAMP中打开,所以你的var_dump可能有点不同的格式,但总的来说你从数组中得到一个php变量,你可以使用foreach
或其他循环进行迭代。
详细了解json_decode here