【问题标题】:function delete_item() from array php来自数组 php 的函数 delete_item()
【发布时间】:2016-05-11 13:23:30
【问题描述】:

为什么这个功能不起作用?调用后,打印出同样的数组。

$myArray1 = ["Barcelona",  "Romania", "Cile", "France"];

function del(&$array, $item_to_del){
    foreach ($array as $item) {
        if ($item == $item_to_del){
            unset($item);

        }
    }
}

del($myArray1, "Barcelona");
var_dump($myArray1);

【问题讨论】:

  • 因为您实际上并没有删除数组中的项目。您正在取消设置 $item

标签: php arrays function element


【解决方案1】:

只需用这个替换你的 del 函数。试试这个:

function del(&$array, $item_to_del){
    if (($key = array_search($item_to_del, $array)) !== false) {
        unset($array[$key]);
    }
}

【讨论】:

  • 如果item重复多次进入数组会发生什么?
【解决方案2】:

您还必须删除index

试试这个:

<?php

$myArray1 = ["Barcelona",  "Romania", "Cile", "France"];

function del(&$array, $item_to_del){
    foreach ($array as $key => $item) {
        if ($item == $item_to_del){
            unset($array[$key]);

        }
    }
}

del($myArray1, "Barcelona");
var_dump($myArray1);

【讨论】:

  • Md Mahfuzur Ra​​hman,谢谢你,这很有效,很酷。但这很奇怪,因为它不是地图。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-07
  • 1970-01-01
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多