从foreach值创建关联数组

时间:2017-07-17 21:21:22

标签: php arrays foreach

我想从foreach循环创建关联数组。

    if (sizeof($ads) > 0) {
    foreach($ads as $social_item) {
        $sdbr .= $social_item['sidebar'];
        $pno .= $social_item['no']; 
       }
       echo $sdbr // cow hen
       echo $pno  // milk egg
    }

如何创建像这样的关联数组?

$out = array("cow"=>"milk","hen"=>"egg");

1 个答案:

答案 0 :(得分:0)

使用sidebar作为关键字,no作为值:

foreach($ads as $social_item) {
    $sdbr = $social_item['sidebar'];
    $pno  = $social_item['no'];
    $out[$sdbr] = $pno;
   }
}
print_r($out);

如果你还需要字符串:

foreach($ads as $social_item) {
    $sdbr .= $social_item['sidebar'];
    $pno  .= $social_item['no'];
    $out[$social_item['sidebar']] = $social_item['no'];
   }
   echo $sdbr // cow hen
   echo $pno  // milk egg
}