简体   繁体   English

使用 unset 从数组中删除创建值

[英]Deleting from array using unset creates values

$array = [ 0, 5, 7 ];

For this array, I want to unset without it assigning a value.对于这个数组,我想在不分配值的情况下unset

When I unset($array[5]) it will return当我unset($array[5])它将返回

{
    "0" => 0,
    "1" => 5,
    "2" => 7
}

But my actual goal is to make it return like但我的实际目标是让它像

[ 0, 7 ]

That way when I use json_encode it will just show up as这样,当我使用json_encode时,它只会显示为

[ 
    0,
    7
]

Is this possible at all?这可能吗? I googled and everyone just mentions indexing, but I am looking at just removing this number from the array.我用谷歌搜索,每个人都只是提到索引,但我正在考虑从数组中删除这个数字。 Not have it reindex or change the formatting of it to have a value.没有它重新索引或更改它的格式以具有值。

The parameter within the brackets on $array[] is actually the numerical index or associative index (arrays in PHP are maps). $array[]上括号内的参数实际上是数字索引或关联索引(PHP 中的数组是映射)。

In your case, you want to do:在你的情况下,你想做:

unset($arr[1]);
$a = [0,5,7];
array_splice($a, 1, 1); // remove from position 1 - remove 1 entry

echo json_encode($a);

Working example .工作示例

output output

[0,7]

references参考

additional informaion附加信息

Unset wont work as is, since it preserves the initial keys. Unset 不会按原样工作,因为它保留了初始键。

A solution with unset is to ignore the keys by using array_values :一个未设置的解决方案是使用array_values忽略键:

$a = [0,5,7];

unset($a[1]);
$a = array_values($a);

echo json_encode($a);

Working example .工作示例

Same output as above.与上述相同的 output。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM