简书链接:json对象和json数组的键值对遍历和转换
文章字数:54,阅读全文大约需要1分钟

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

$arr = array("name" => 'qssq', "age" => 18);


foreach ($arr as $key => $value) {
echo "key: $key,value:$value";
}

//$json=json_decode($jsonStr);//json字符串转json对象
$json= json_decode(json_encode($arr));//arr数组转json字符串再转对象
$type=gettype($json);
echo "type: $type \n";
foreach ($json as $key => $value) {
echo "key: $key,value:$value";
}

输出结果

1
2
3
4
5
D:\phpStudy\php\php-7.0.12-nts\php.exe D:\phpStudy\WWW\tp5\client\test.php
key: name,value:qssqkey: age,value:18type: object
key: name,value:qssqkey: age,value:18
Process finished with exit code 0

对象 或者json对象转数组

1
2
3
4
5
6
7
8
9
10
11
12

//PHP stdClass Object转array
function object_array($array) {
if(is_object($array)) {
$array = (array)$array;
} if(is_array($array)) {
foreach($array as $key=>$value) {
$array[$key] = object_array($value);
}
}
return $array;
}