【问题标题】:How to find object in php array and delete it?如何在php数组中找到对象并删除它?
【发布时间】:2023-04-01 17:46:01
【问题描述】:

这是我的数组的 print_r 输出:

Array
(
[0] => stdClass Object
    (
        [itemId] => 560639000019
        [name] => Item no1
        [code] => 00001
        [qty] => 5
        [id] => 2
    )

[1] => stdClass Object
    (
        [itemId] => 470639763471
        [name] => Second item
        [code] => 76347
        [qty] => 9
        [id] => 4
    )

[2] => stdClass Object
    (
        [itemId] => 56939399632
        [name] => Item no 3
        [code] => 39963
        [qty] => 6
        [id] => 7
    )

)

如何找到具有 [id] => 4 的对象的索引以便将其从数组中删除?

【问题讨论】:

  • 奇怪的是,在取消设置数组项后,它会破坏 json_encode,因此输出变得无法使用。

标签: php arrays


【解决方案1】:
foreach($parentObj AS $key=>$element){
  if ($element->id == THE_ID_YOU_ARE_LOOKING_FOR){
    echo "Gottcha! The index is - ". $key;
  }
}

$parentObj 显然是您的根数组 - 包含所有其他数组。

我们使用foreach 循环遍历每个项目,然后根据您想要的值测试​​它的id 属性。一旦我们有了它 - 我们所在的 $key 就是您要查找的索引。

【讨论】:

  • 等等 .. $element 不是一个对象?
  • @lax - 我没听懂……你什么意思?变量$element 引用数组中的一个元素...
  • $element 是 stdClass 的一个实例。查看问题
  • @lax - 我想我明白你的意思了 - 这是你访问该物业的方式。我使用了与关联数组相同的方法...我的 OO PHP 不是那么强大...但感谢您的评论。不过,多一点解释会大有帮助......
  • @Lix 谢谢,你的回答也很棒。我选择另一个只是因为我必须选择一个更“完整”。
【解决方案2】:
$found = false;  
foreach($values as $key => $value) {
    if ($value->id == 4) {
        $found = true;
        break;
    }
}

if ($found) unset($values[$key]);

这被认为比任何其他解决方案都更快,因为我们只迭代 array 直到找到要删除的对象。

注意:您不应该在迭代时删除数组的元素,所以我们稍后会在此处进行。

【讨论】:

  • 我不确定在迭代时不删除数组元素的规则。在另一个question 中,用户指出在 PHP 中这样做是完全可以的,那么有什么来源吗?因为到目前为止没有人真正指出原因,只是说出来。
  • 对我来说,它给出了找不到对象的错误,所以我这样做了$value['id']
【解决方案3】:

试试这个

foreach($array AS $key=>$object){
   if($object['id'] == 4){
       $key_in_array = $key;
   }
}

// chop it from the original array
array_slice($array, $key_in_array, 1);

【讨论】:

  • 这与我想要的几乎完全相反:)
【解决方案4】:
foreach( $arr as $k=>&$a) {
    if( $a['id'] == 4 )
        unset($arr[$k]);
}

【讨论】:

  • 你不应该改变你当前正在迭代的数组!
  • @fdomig 如果有多个id 4 的孩子怎么办?
  • @fdomig 你不能这么肯定。
  • 在迭代过程中你永远不应该接触数组本身。然后,您最好将每个找到的索引添加到 $found 数组中,然后删除所有键。
  • 感谢您的提示。会跟随它。虽然我仍然不明白它背后的意义。 @fdomig
【解决方案5】:

实现结果的另一种方法是使用array_filter

$array = array(
    (object)array('id' => 5),
    (object)array('id' => 4),
    (object)array('id' => 3)
);
$array = array_filter($array, function($item) {
    return $item->id != 4;
});
print_r($array);

【讨论】:

  • 这是一个很好的解决方案,但是您正在迭代整个集合,尽管大多数时候没有必要。
  • 没错,这取决于有多少元素要取消设置的情况和确定性。虽然非常有用的功能。
【解决方案6】:

使用array_search

$a = new stdClass;
$b = new stdClass;
$a->id = 1;
$b->id = 2;

$arr = array($a, $b);
$index = array_search($b, $arr);

echo $index;
// prints out 1

【讨论】:

    【解决方案7】:

    这是我的解决方案。鉴于,它有点 hackish,但它会完成工作。

    搜索(数组 $items, 混合 $id[, &$key]);

    返回由$id 找到的项目。如果您添加变量$key,它将为您提供找到的项目的密钥。

    function search($items, $id, &$key = null) {
      foreach( $items as $item ) {
        if( $item->id == $id ) {
          $key = key($item);
          return $item;
          break;
        }
      }
    
      return null;
    }
    

    用法

    $item = search($items, 4, $key);
    unset($items[$key]);
    

    注意:这可以修改为允许自定义键并返回共享相同值的多个项目。

    I've created an example so you can see it in action.

    【讨论】:

      【解决方案8】:

      一个有趣的选择

      $getIdUnset = function($id) use ($myArray)
      {
          foreach($myArray as $key => $obj) {
              if ($obj->id == $id) {
                  return $key;
              }
          }
      
          return false;
      };
      
      if ($unset = $getIdUnset(4)) {
          unset($myArray[$unset]);
      }
      

      【讨论】:

        【解决方案9】:

        目前 php 还没有任何支持的函数。

        所以参考 Java 的 Vector,或者 jQuery 的 $.inArray(),它就是:

        public function indexOf($object, array $elementData) {
            $elementCount = count($elementData);
            for ($i = 0 ; $i < $elementCount ; $i++){
                if ($object == $elementData[$i]) {
                    return $i;   
                }
            }
            return -1;
        }
        

        您可以将此功能保存为核心功能供以后使用。

        【讨论】:

          【解决方案10】:

          就我而言,这是我的数组$array
          我对我的项目的这个问题感到困惑,但这里的一些答案帮助了我。

          array(3) { 
                     [0]=> float(-0.12459619130796) 
                     [1]=> float(-0.64018439966448) 
                     [2]=> float(0)
                   }
          

          然后使用if condition 停止循环

          foreach($array as $key => $val){
                     if($key == 0){ //the key is 0
                         echo $key; //find the key
                         echo $val; //get the value
                     }
                  }
          

          【讨论】:

            【解决方案11】:

            我知道,经过这么多年,这可能是一个无用的答案,但为什么不呢?

            这是我个人对可能的index_of 的实现,使用与其他答案相同的代码,但让程序员选择何时以及如何进行检查,也支持复杂的检查。

            if (!function_exists('index_of'))
            {
                /**
                 * @param iterable $haystack
                 * @param callable $callback
                 * @param mixed|null &$item
                 * @return false|int|string
                 */
                function index_of($haystack, $callback, &$item = null)
                {
                    foreach($haystack as $_key => $_item) {
                        if ($callback($_item, $_key) === true) {
                            $item = $_item;
                            return $_key;
                        }
                    }
                    return false;
                }
            }
            

            【讨论】:

              猜你喜欢
              • 2017-08-03
              • 1970-01-01
              • 2016-01-10
              • 2013-03-04
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2011-04-04
              • 1970-01-01
              相关资源
              最近更新 更多