2015-11-04 131 views
1

我試圖將數組插入到其他數組中,問題是當我調用array_push()方法覆蓋數組的最後一個元素時,我只是得到一個數組一個數組(最後一個)的數據:PHP將數組插入到多維數組中被覆蓋

$users_data = []; 
    $resultSize = count($result); 

    $data = $result; 

    for ($i = 0; $i < $resultSize; $i++) { 
     $person = [ 
      'nombre'   => $result[$i]['nombre'], 
      'apellido'  => $result[$i]['apellido'], 
     ]; 
     array_push($users_data, $person); 
     // $users_data = $person; I also have tried with this method. 
    }; 

我剛剛收到一個對象與此:

Object {nombre: jane, apellido: doe} 

到底哪裏出問題了?

回答

3

它shud是這樣的,

$person['nombre'][$i] = $result[$i]['nombre']; 
$person['apellido'][$i] = $result[$i]['apellido']; 
       ^you have missed this index. 

那麼沒有必要的array_push()。您可以直接分配給personsuser_data

+0

謝謝!它工作完美! –

+0

@LeonardoCavani考慮接受答案,如果它有幫助。 –

+0

我需要8分鐘做XD。謝謝 ! –

0

或者這樣:

for ($i = 0; $i < $resultSize; $i++) { 
    $users_data['nombre'][] = $result[$i]['nombre']; 
    $users_data['apellido'][] = $result[$i]['apellido']; 
};