How to find index of object in php array?

前端 未结 10 1861
时光说笑
时光说笑 2021-02-13 18:46

Here is print_r output of my array:

Array
(
[0] => stdClass Object
    (
        [itemId] => 560639000019
        [name] => Item no1
        [code] =>         


        
10条回答
  •  隐瞒了意图╮
    2021-02-13 19:14

    Here's my solution. Given, it is a bit hackish, but it will get the job done.

    search(array $items, mixed $id[, &$key]);

    Returns the item that was found by $id. If you add the variable $key it will give you the key of the item found.

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

    Usage

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

    Note: This could be modified to allow a custom key and return multiple items that share the same value.

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

提交回复
热议问题