PHP - Extracting a property from an array of objects

前端 未结 10 943
时光取名叫无心
时光取名叫无心 2020-12-02 05:16

I\'ve got an array of cats objects:

$cats = Array
    (
        [0] => stdClass Object
            (
                [id] => 15
            ),
                 


        
相关标签:
10条回答
  • 2020-12-02 05:18
    function extract_ids($cats){
        $res = array();
        foreach($cats as $k=>$v) {
            $res[]= $v->id;
        }
        return $res
    }
    

    and use it in one line:

    $ids = extract_ids($cats);
    
    0 讨论(0)
  • 2020-12-02 05:18

    Warning create_function() has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

    Builtin loops in PHP are faster then interpreted loops, so it actually makes sense to make this one a one-liner:

    $result = array();
    array_walk($cats, create_function('$value, $key, &$result', '$result[] = $value->id;'), $result)
    
    0 讨论(0)
  • 2020-12-02 05:21

    You can do it easily with ouzo goodies

    $result = array_map(Functions::extract()->id, $arr);
    

    or with Arrays (from ouzo goodies)

    $result = Arrays::map($arr, Functions::extract()->id);
    

    Check out: http://ouzo.readthedocs.org/en/latest/utils/functions.html#extract

    See also functional programming with ouzo (I cannot post a link).

    0 讨论(0)
  • 2020-12-02 05:25
    // $array that contain records and id is what we want to fetch a
    $ids = array_column($array, 'id');
    
    0 讨论(0)
  • 2020-12-02 05:26
        $object = new stdClass();
        $object->id = 1;
    
        $object2 = new stdClass();
        $object2->id = 2;
    
        $objects = [
            $object,
            $object2
        ];
    
        $ids = array_map(function ($object) {
            /** @var YourEntity $object */
            return $object->id;
            // Or even if you have public methods
            // return $object->getId()
        }, $objects);
    

    Output: [1, 2]

    0 讨论(0)
  • 2020-12-02 05:27

    Warning create_function() has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

    You can use the array_map() function.
    This should do it:

    $catIds = array_map(create_function('$o', 'return $o->id;'), $objects);
    
    0 讨论(0)
提交回复
热议问题