json对象和json数组的键值对遍历和转换


$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";
}

输出结果

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对象转数组


//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;  
}

你可能感兴趣的:(json对象和json数组的键值对遍历和转换)