'array_column'难度

时间:2014-12-12 19:34:59

标签: php arrays

我按如下方式构建了一个数组:

while($row = mysqli_fetch_array($result))
  {
 $universe[] = $row;
}

print_r输出如下:

Array ( [0] => 
   Array ( [0] => 1 [ID] => 1 [1] => Russian Federation - Conventional [Misc1] => Russian Federation - Conventional [2] => RUS.Con1 [Misc2] => RUS.Con1 [3] => [Misc3] => [4] => [Misc4] => [5] => 13.13 [1980] => 13.13 [1981] => 13.13 [1982] => 13.13 [1983] => 13.13 [1984] => 13.13 [1985] => 13.13 [1986] => 13.13) 
        [1] => 
   Array ( [0] => 2 [ID] => 2 [1] => Saudi Arabia - Conventional [Misc1] => Saudi Arabia - Conventional [2] => SAU.Con1 [Misc2] => SAU.Con1 [3] => [Misc3] => [4] => [Misc4] => [5] => 4.47 [1980] => 4.47 [1981] => 4.47 [1982] => 4.47 [1983] => 4.47 [1984] => 4.47 [1985] => 4.47 [1986] => 4.47 ) etc ...

我现在正在尝试在[1980]列中获取所有值的数组。所以我执行以下操作,但得到一个空白。有任何想法吗?另外 - 为什么我得到一个不必要的阵列包装一切?

print_r($universe);
$hi = array_column($universe, '1980');
print_r($hi); 

3 个答案:

答案 0 :(得分:1)

你的数组中有一个数组。

print_r($universe);
$hi = array_column($universe[0], '1980');
print_r($hi); 

答案 1 :(得分:1)

尝试这种方式:

$values = array();
for ($i=0;$i<count($universe);$i++){
    $values[] = $universe[$i]['1980'];
}

在while循环中避免多次迭代:

$values = array();
while($row = mysqli_fetch_array($result)){
    $universe[] = $row;
    $values[] = $row['1980'];    
}

答案 2 :(得分:0)

你的数组结构是完全无法解释的,所以我甚至不打算进入实际的代码。

但请记住,$array[1980]$array['1980']不是一回事。 array_column

也是如此

PS。这就是数组的样子:

$array = array(
    array(
        'a' => 'b',
        'c' => 'd',
        ...
        'y' => 'z'
    ),
    array(
        'a' => '1',
        'c' => '3',
        ...
        'y' => '26'
    ),
    ...
);