2013-07-28 74 views
1

我使用CakePHP和檢索用戶信息的多維數組,進行計算,然後我想的是計算加入到每個用戶推值與PHP

陣列查找用戶後,這是數組

print_r($user_info); 

Array 
(
    [0] => Array 
     (
      [User] => Array 
       (
        [id] => 1 
        [email] => [email protected] 
        [website] => www.admin.com 

       ) 

     ) 

) 

現在,我想在一個循環

array_push($user_info[$i]['User'],array('num_payments' => $customer_payments[$i]['num_payments'])); 

這裏補充一個「num_payments」鍵這個特定用戶的該結構的結果數組

Array 
(
    [0] => Array 
     (
      [User] => Array 
       (
        [id] => 1 
        [email] => [email protected] 
        [website] => www.admin.com 
        [0] => Array 
         (
          [num_payments] => 1 
         ) 

       ) 

     ) 

) 

我怎樣才能把它變成這個結構?

Array 
(
    [0] => Array 
     (
      [User] => Array 
       (
        [id] => 1 
        [email] => [email protected] 
        [website] => www.admin.com 
        [num_payments] => 1 
       ) 

     ) 

) 

回答

3

沒有array_push

$user_info[$i]['User']['num_payments'] = $customer_payments[$i]['num_payments']; 
+0

所以才遍歷值? – user1443519

+0

是 - 對於每個用戶 - 只需將num_payments'鍵添加到數組 –

+0

哇,這很明顯。有時間離開鍵盤。謝謝! – user1443519

1
$user_info[$i]['User']['num_payments'] = $customer_payments[$i]['num_payments']; 
1

這聽起來像你應該在join添加到您的查詢與用戶數據相結合的數據拉。然後,您可以使用Hash::combine方法將數據合併到它所屬的數組中。

不過,如果你只是運行在數據的循環,你應該能夠將其添加喜歡:

foreach ($user_info as $i -> $data) { 
    $user_info[$i]['User']['num_payments'] = $customer_payments[$i]['num_payments']; 
} 

這是假設$i對應於兩個陣列相同的記錄。

如果$i$customer_payments對應User.id,那麼它會要求你這樣做:

foreach ($user_info as $i -> $data) { 
    $user_info[$i]['User']['num_payments'] = $customer_payments[$user_info[$i]['User']['id']]['num_payments']; 
}