2016-04-15 187 views
18

我敢肯定,這是預期的行爲爲array_column()PHP array_column()沒有返回對象falsy值

class myObj { 
    public $prop; 
    public function __construct(int $prop) { 
     $this->prop = $prop; 
    } 
} 

$objects = [ 
    new myObj(7), 
    new myObj(3), 
    new myObj(8), 
    new myObj(0), 
    new myObj(2), 
    new myObj(6) 
]; 

echo '<pre>'; 
print_r(array_column($objects, 'prop')); 
echo '</pre>'; 

返回:

Array (
    [0] => 7 
    [1] => 3 
    [2] => 8 
    [3] => 2 
    [4] => 6 
) 

0丟失。也許它在內部使用empty() ..?

0false可以是正常的有效對象屬性值並且array_column()用於返回值時,它爲什麼不返回錯誤值?

什麼是最好的解決方法..?

+1

似乎是我的錯誤。 – Rizier123

+0

哪個PHP版本? –

+0

在Windows/IIS上的PHP 7.0.0 ... –

回答

6

這當然似乎是一個錯誤,我由對象數組轉換爲一個嵌套的數組倒是report it as such

您可以變通圍着它

print_r(array_column(json_decode(json_encode($objects), true), 'prop')); 
+0

我不太瞭解PHP內部,但我認爲這是因爲:http://lxr.php。 net/xref/PHP_7_0/ext/standard/array.c#3569跳過「空」PHP值。我也可能是錯誤的 – Rizier123

+1

@ Rizier123 - 看起來好像它會消除與null相比的任何值的效果(並且該錯誤還會影響有效的空值和布爾值false)....更好地簡單地測試該屬性是否存在;我可能會在這個週末做一個PR –

+0

是的,這就是我的意思是*「空」的PHP值* :)我還用空字符串進行了測試,結果沒有顯示出來。可悲的是,我對內部解決方案不夠了解。 – Rizier123