2016-09-06 38 views
-1

上午將元素添加到一個數組試圖推動元素添加到array但他們失敗通過array_push

這是我曾嘗試:

$relations=['0'=>'']; 
    $hhrelations = Tblsuhhrelationship::model()->findAll(); 
    foreach ($hhrelations as $key=>$hhrelation){ 

     array_push($relations, $hhrelation['description'],(int)$hhrelation['hh_relation_id']); 

    } 
    var_dump($relations) 

由此,在這種形式的數組:

1 => string 'Head' (length=4) 
    2 => int 1 
    3 => string 'Spouse' (length=6) 
    4 => int 2 
    5 => string 'Child (own/Step)' (length=16) 
    6 => int 3 
    7 => string 'Parent/Parent in-law' (length=20) 
    8 => int 4 
    9 => string 'Brother/Sister' (length=14) 
10 => int 5 
    11 => string 'Other Relatives' (length=15) 
    12 => int 6 
    13 => string 'Unrelated' (length=9) 
    14 => int 7 

我想它是:

1 => string 'Head' (length=4) 
    2 => string 'Spouse' (length=6) 
    3 => string 'Child (own/Step)' (length=16) 
    4 => string 'Parent/Parent in-law' (length=20) 
    5 => string 'Brother/Sister' (length=14) 
//Others continue this way 

當值1,2,3..$hhrelation['hh_relation_id']

給出的字符串被$hhrelation['description']

給出如何修改呢?

回答

2

使用array_push而不是簡單賦值的任何特定原因?

$relations[(int)$hhrelation['hh_relation_id'])] = $hhrelation['description']; 

array_push從字面上爲列表中的每個項目創建一個條目,因此您在轉儲中看到了什麼。

+0

謝謝,工作不好,把它標記爲正確 –

1

嘗試

foreach ($hhrelations as $key=>$hhrelation){ 

    $relations[(int)$hhrelation['hh_relation_id']] = $hhrelation['description']; 

} 
1

除了以前的答案,如果你正在使用Yii2可以使用ArrayHelper創建映射爲您服務。

use yii\helpers\ArrayHelper; 

$relations = ArrayHelper::map($hhrelations, 'hh_relation_id', 'description'); 
+0

謝謝,但我使用yii1,但虐待使用yii2 –