php indexed array and associative array

Recently encountered a bug, record it


//define an array
$arr = Array('a','b','c','d');

// Convert to json string
$str1 = json_encode($arr);

// remove an item
unset($arr[1]);

// turn to json
$str2 = json_encode($arr);


var_dump($str1);
echo '<br/>';
var_dump ($ str2);
 
 
string(17) "["a","b","c","d"]"
string(25) "{"0":"a","2":"c","3":"d"}"
The print result shows that one is an array and the other is an object.

Obviously the first is an indexed array and the second is an associative array. Indexed array to json is an array, and associative array to json is an object.

Directly using unset() to delete an array element will convert the index array into an associative array

A method to remove an element, keeping the index:

unset($arr[1]);
array_values($arr);
array_splice($array, 1, 1);





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324805227&siteId=291194637