使用php在循环中修改数组

时间:2014-07-16 12:57:00

标签: php arrays

我有一个php多维数组(A),我想从该数组A构建另一个数组(B)

我的代码是

$question = array(
    "ques_15" => array(
        "name" => array(
            "0" => "aaa"
        )
    ),
    "ques_16" => array(
        "name" => array(
            "0" => "bbb",
            "1" => "ccc"
        )
    )
);
$i=0;
foreach($question as $k=>$v)
{
    list(,$qid) = explode("_",$k);
    $filename .= $question[$k]['name'][$i]."#&";
    $insertData[]  = array(':quid'=>$qid,':answer'=>$filename);
    $i++;
}
echo '<pre>';
print_r($insertData);
echo '</pre>';

打印

Array
(
    [0] => Array
        (
            [:quid] => 15
            [:answer] => aaa#&
        )

    [1] => Array
        (
            [:quid] => 16
            [:answer] => aaa#&ccc#&
        )

)

但我希望它是

Array
(
    [0] => Array
        (
            [:quid] => 15
            [:answer] => aaa
        )

    [1] => Array
        (
            [:quid] => 16
            [:answer] => aaa#&ccc
        )

)

3 个答案:

答案 0 :(得分:4)

$i=0;

foreach($question as $k=>$v)
{
    list(,$qid) = explode("_",$k);   
    $insertData[$i][':quid'] = $qid;
    $insertData[$i][':answer'] = implode('#&',$v['name']);
    $i++;
}

答案 1 :(得分:3)

$filename .= (empty($filename) ? '' : '#&') . $question[$k]['name'][$i];

如果aaa#&ccc是拼写错误而且应该是bbb#&ccc,那么您可以这样做:

foreach($question as $k=>$v)
{
    list(,$qid) = explode("_",$k);
    $filename = implode("#&", $v['name']);
    $insertData[]  = array(':quid'=>$qid,':answer'=>$filename);
}

答案 2 :(得分:0)

删除&#34;#&amp;&#34;并把它放在条件。它会起作用;

添加条件。

$filename .= $question[$k]['name'][$i];
if(!empty($filename)){
  $filename .= '#&';
}