dongpo9071
dongpo9071
2014-07-16 12:57

使用php在循环中修改数组

已采纳

I have a php multidimensional array(A) and I want to build another array(B) from that array A

My code is

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

It prints

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

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

)

But I want it to be

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

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

)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • dsgwii4867 dsgwii4867 7年前
    $filename .= (empty($filename) ? '' : '#&') . $question[$k]['name'][$i];
    

    If aaa#&ccc is a typo and it should be bbb#&ccc, then you can simply do:

    foreach($question as $k=>$v)
    {
        list(,$qid) = explode("_",$k);
        $filename = implode("#&", $v['name']);
        $insertData[]  = array(':quid'=>$qid,':answer'=>$filename);
    }
    
    点赞 评论 复制链接分享
  • dqyin0101 dqyin0101 7年前

    Remove "#&" and place it in condition. It will work;

    Just Add a condition.

    $filename .= $question[$k]['name'][$i];
    if(!empty($filename)){
      $filename .= '#&';
    }
    
    点赞 评论 复制链接分享
  • douli1854 douli1854 7年前
    $i=0;
    
    foreach($question as $k=>$v)
    {
        list(,$qid) = explode("_",$k);   
        $insertData[$i][':quid'] = $qid;
        $insertData[$i][':answer'] = implode('#&',$v['name']);
        $i++;
    }
    
    点赞 评论 复制链接分享