通过array_push向数组添加元素

时间:2016-09-06 05:48:48

标签: php arrays yii

我试图将元素推送到array但却失败了

这就是我的尝试:

  $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']

给出

我该如何修改?

3 个答案:

答案 0 :(得分:2)

使用array_push而不是简单赋值的任何特殊原因?

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

array_push实际上是在列表中为每个项目创建一个条目,因此您在转储中看到的内容。

答案 1 :(得分:1)

尝试

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

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

 }

答案 2 :(得分:1)

除了之前的答案,如果您使用的是Yii2,您可以使用ArrayHelper为您创建映射。

use yii\helpers\ArrayHelper;

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