2017-06-20 48 views
1

假設我有一個由某個ID鍵入的記錄數組,我使用array_column()從每條記錄中提取一條數據。

$records = array(
1234 => array(
    'first_name' => 'John', 
    'last_name' => 'Doe', 
), 
4567 => array(
    'first_name' => 'Sally', 
    'last_name' => 'Smith', 
), 
); 

array_columns($ input,'first_name')的結果是一個數值索引的數組。有沒有辦法保持輸入數組的密鑰?

+1

'$ newArray = array_combine(array_keys($記錄),array_column($記錄, '如first_name'));' –

+2

[PHP陣列的可能的複製\ _column與unsequential索引返回錯索引](https://stackoverflow.com/questions/37270002/php-array-column-with-unsequential-index-returns-wrong-index) – oguzhancerit

回答

0

當id在數據數組中也可用時,可以使用array_column的第三個參數。

例如: array_column($records, 'first_name', 'id');

+2

對不起,我應該說清楚 - 所需的數據不可用在數組中,只能作爲鍵。 – joachim

相關問題