Reputation: 1437
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
)
)
Upvotes: 0
Views: 68
Reputation: 1
Remove "#&" and place it in condition. It will work;
Just Add a condition.
$filename .= $question[$k]['name'][$i]; if(!empty($filename)){ $filename .= '#&'; }
Upvotes: 0
Reputation: 15087
$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);
}
Upvotes: 3
Reputation: 304
$i=0;
foreach($question as $k=>$v)
{
list(,$qid) = explode("_",$k);
$insertData[$i][':quid'] = $qid;
$insertData[$i][':answer'] = implode('#&',$v['name']);
$i++;
}
Upvotes: 4