我正在读取一个json文件并将其转换为一个assoc数组。在json里面是[]
类型的数组,它们的键是一个基于0的索引系统。当我从[]
数组中删除一个值后尝试将关联数组写回json时,会将[1, 2, 3, 4, 5, 6, 7, 8]
转换为{"0": 1, "1": 2, "2": 3, "3": 4, "4": 5, "6": 7, "7": 8}
有没有人知道为什么会这样做?我将在下面包含我的PHP代码:
<?php
function json_removeItemType($arrayid, $itemid) {
$json = json_read();
if($json) {
echo "<p>json true</p>";
foreach($json as $key => &$value) {
echo "<p>in 1st foreach loop</p>";
if($key == $arrayid) {
echo "<p>key == arrayid<p>";
foreach($value as &$v) {
echo "<p>In second foreach loop</p>";
if($v == $itemid) {
echo "<p>unsetting value</p>";
unset($v);
echo "value unset";
}
}
}
}
$json = json_write($json);
if($json) {
echo "<p>json written</p>";
return true;
} else {
return false;
}
} else {
return false;
}
}
function json_write($assoc) {
try {
$json = fopen("../data.json", "w");
echo "<p>" . var_dump($assoc) . "</p>";
$data = json_encode($assoc);
echo "<p>$data</p>";
fwrite($json, $data);
fclose($json);
return true;
} catch(Exception $e) {
return false;
}
}
function json_read() {
$file = fopen("../data.json", "r");
$len = filesize("../data.json");
$data = fread($file, $len);
$json = (array) json_decode($data);
return $json;
}
if(json_removeItemType("1", 7)) {
echo "true";
} else {
echo "false";
}
?>