0

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 Answers 3

4
$i=0;

foreach($question as $k=>$v)
{
    list(,$qid) = explode("_",$k);   
    $insertData[$i][':quid'] = $qid;
    $insertData[$i][':answer'] = implode('#&',$v['name']);
    $i++;
}
Sign up to request clarification or add additional context in comments.

Comments

3
$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);
}

4 Comments

Thanks but the answer key is getting blank :(
@Raj then explain why do you want aaa#&ccc and not bbb&ccc? Works here
Extremely sorry yes that's a typo, it should be bbb&ccc
Awesome...brilliant!!...it worked using implode...thanks a lot @meze
0

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

Just Add a condition.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.