Home >Backend Development >PHP Tutorial >Multidimensional array json_encode produces objects instead of arrays
The json_encode function can encode PHP arrays, and the return value is a string in json format. For json_encoding multi-dimensional arrays, I always thought it was returning an array form (in the form of {{obj1}, {obj2}, {obj3}}), but today the interface returned to the client found that it became an object instead of an array ( In the shape of [{....},{.....},{.....}]), it is inconvenient for client operations. After checking the code, I found that I had previously unset the first element of the multi-dimensional array. Units have been deleted, resulting in different return results. Look at the code below:
$arr = array( <span style="white-space:pre"> </span>0=>array('name'=>'张三','age'=>'120'), <span style="white-space:pre"> </span>1=>array('name'=>'李四','age'=>'111'), <span style="white-space:pre"> </span>2=>array('name'=>'王五','age'=>'233') ); $res = json_encode($arr); echo "<script>console.log('$res');</script>";The results are as follows:
Look again after removing the first index:
$arr = array( 0=>array('name'=>'张三','age'=>'120'), 1=>array('name'=>'李四','age'=>'111'), 2=>array('name'=>'王五','age'=>'233') ); unset($arr[0]); $res = json_encode($arr); echo "<script>console.log('$res');</script>";
The solution is to use the sort function to index again.
$arr = array( 0=>array('name'=>'张三','age'=>'120'), 1=>array('name'=>'李四','age'=>'111'), 2=>array('name'=>'王五','age'=>'233') ); unset($arr[0]); sort($arr); $res = json_encode($arr); echo "<script>console.log('$res');</script>";
Okay... This doesn’t seem to be worth writing a blog, just think of it as a reminder to yourself
The above introduces the problem of generating objects instead of arrays after multi-dimensional array json_encode, including aspects of the problem. I hope it will be helpful to friends who are interested in PHP tutorials.