Alternate to array_column()

前端 未结 6 1451
我寻月下人不归
我寻月下人不归 2020-12-02 18:57

I have used array_column() in a project, and after uploading I found out that only PHP 5.5 or above support this function, and I think the hosting I use don\'t

6条回答
  •  情歌与酒
    2020-12-02 19:16

    You can also use array_map() function if you haven't array_column() because of PHP<5.5:

    Example:

    $a = array(
        array(
            'id' => 2135,
            'first_name' => 'John',
            'last_name' => 'Doe',
        ),
        array(
            'id' => 3245,
            'first_name' => 'Sally',
            'last_name' => 'Smith',
        )
    );
    
    array_column($a, 'last_name');
    

    Becomes:

    array_map(function($element) {
      return $element['last_name'];
    }, $a);
    

    So it your case the code will be:

    array_count_values(
      array_map(function($arr) use ($idForBar) {
        return $arr[$idForBar];
      }, $queryResultArray)
    );
    

    This above is working on PHP 5.3.0 and above!

    If you have < PHP 5.3.0, as you wrote PHP 5.2.17, just use simple function:

    function get_field_data($array, $field, $idField = null) {
        $_out = array();
    
        if (is_array($array)) {
            if ($idField == null) {
                foreach ($array as $value) {
                    $_out[] = $value[$field];
                }
            }
            else {
                foreach ($array as $value) {
                    $_out[$value[$idField]] = $value[$field];
                }
            }
            return $_out;
        }
        else {
            return false;
        }           
    }
    

    And the usage:

    $output = get_field_data($queryResultArray, $idForBar);
    

提交回复
热议问题