Slicing a multi-dimensional PHP array across one of its elements

后端 未结 10 867
再見小時候
再見小時候 2020-12-28 15:51

Say for example you just queried a database and you recieved this 2D array.

$results = array(
    array(\'id\' => 1, \'name\' => \'red\'  , \'spin\' =&         


        
相关标签:
10条回答
  • 2020-12-28 16:48

    Simply put, no.

    You will need to use a loop or a callback function like array_walk.

    0 讨论(0)
  • 2020-12-28 16:49

    I voted @Devon's response up because there really isn't a way to do what you're asking with a built-in function. The best you can do is write your own:

    function array_column($array, $column)
    {
        $ret = array();
        foreach ($array as $row) $ret[] = $row[$column];
        return $ret;
    }
    
    0 讨论(0)
  • 2020-12-28 16:51

    I think this will do what you want

    array_uintersect_uassoc

    You would have to do something like this

    $results = array(
        array('id' => 1, 'name' => 'red'  , 'spin' =>  1),
        array('id' => 2, 'name' => 'green', 'spin' => -1),
        array('id' => 3, 'name' => 'blue' , 'spin' => .5)
    );
    $name = array_uintersect_uassoc( $results, array('name' => 'value')  , 0, "cmpKey");
    print_r($name);
    
    //////////////////////////////////////////////////
    // FUNCTIONS
    //////////////////////////////////////////////////
    function cmpKey($key1, $key2) {
      if ($key1 == $key2) {
        return 0;
      } else {
        return -1;
      }
    }
    

    However, I don't have access to PHP5 so I haven't tested this.

    0 讨论(0)
  • 2020-12-28 16:51

    This is fast function alternative of array_column()

    if(!function_exists('array_column')) {
        function array_column($element_name) {
            $ele =   array_map(function($element) {
                return $element[$element_name];
            }, $a);
            return  $ele;
        }
    }
    
    0 讨论(0)
提交回复
热议问题