从Json数组中删除一个元素 [英] Remove an element from Json array
问题描述
我将数组内容以json数组的形式存储到数据库中.
I stored my array content in form of json array to database .
格式:["1","2","3"]
Format: ["1","2","3"]
现在,我从数据库中检索了值,并尝试从同一结构中删除第三个元素"2".
Now i retrieved the value from database and tried to remove the third element "2" from same structure.
我的代码是
$numbers= json_decode($numbers_db,true); //json decode numbers array got from DB
if (($key = array_search(2, $numbers)) !== false) {
unset($numbers[$key]);
}
$numbers_final = json_encode($numbers);
现在我希望$ numbers_final的格式为:["1","3"]
Now i expected $numbers_final to be of the format: ["1","3"]
但是它导致了{"0":"1","2":"3"}
推荐答案
问题是,当您unset()
元素时,索引保持不变.在这种情况下,索引1
不再存在,因此该数组将转换为对象.
The problem is that when you unset()
an element, the indexes are kept intact. In this case, the index 1
doesn't exists anymore so the array is converted into an object.
要强制对数组进行顺序重新索引,您可以执行以下操作:
To force the array to be re-indexed sequentially yo can do something like this:
$numbers_db = '["1", "2", "3"]';
echo $numbers_db;
$numbers= json_decode($numbers_db,true); //json decode numbers ar
if (($key = array_search(2, $numbers)) !== false) {
unset($numbers[$key]);
$numbers = array_values($numbers);
}
$numbers_final = json_encode($numbers);
echo $numbers_final;
这篇关于从Json数组中删除一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!