我如何组合数组?

时间:2016-03-10 05:37:47

标签: php arrays

我有这个数组:

Array (
    [question_id] => Array ( [0] => 4 [1] => 4 [2] => 4 [3] => 4 [4] => 4 [5] => 4 [6] => 4 [7] => 4 ) 
    [result_branch] => Array ( [0] => 126 [1] => 130[2] => 134 [3] => 1232 [4] => 128134 [5] => 16 [6] => 128134 [7] => 12136 
    [text] => Array ( [0] => 3213 [1] => qweq [2] => wdas [3] => d [4] => cxzc [5] => xzczx [6] => czx [7] => saed )  )

我需要的是:

Array (array([question_id]=>4,[result_branch]=>126,[text]=>3213 ),
    array([question_id]=>4,[result_branch]=>130,[text]=>qweq ),
    array([question_id]=>4,[result_branch]=>134 ,[text]=>wdas ),
    array([question_id]=>4,[result_branch]=>1232 ,[text]=>d ),
...
    array([question_id]=>4,[result_branch]=>12136 ,[text]=>saed )

)

我怎样才能得到这个结果?

2 个答案:

答案 0 :(得分:2)

$oldarray = array(/*Old values*/);
$newarray = array();
for($i = 0; $i<count($oldarray['question_id']); $i++)
{
    $newarray[] = array(
        "question_id"=>$oldarray['question_id'][$i],
        "result_branch"=>$oldarray['result_branch'][$i],
        "text"=>$oldarray['text'][$i]
    );
}

这应循环遍历所有旧数组,并使用每个question_id,result_branch和text的新单元格将它们放入新格式。

答案 1 :(得分:0)

你可以通过简单的逻辑改变键来实现它

这是使用输入法的代码

<?php
// $a is your array 
// $b is your desired format 
// $c is the result after converting $a to $c 
$a['question_id'] = array (4,4,4,4,4,4,4,4 );
$a['result_branch'] = array(126,130,134,1232,128134,16,128134,12136);
$a['text'] = array("3213" ,"qweq","wdas" ,"d" ,"cxzc" ,"xzczx","czx","saed");
$b[0]['question_id'] = 4;
$b[1]['question_id'] = 4;
$b[2]['question_id'] = 4;
$b[3]['question_id'] = 4;
$b[4]['question_id'] = 4;
$b[5]['question_id'] = 4;
$b[6]['question_id'] = 4;
$b[7]['question_id'] = 4;

$b[0]['result_branch'] = 126;
$b[1]['result_branch'] = 130;
$b[2]['result_branch'] = 134;
$b[3]['result_branch'] = 1232;
$b[4]['result_branch'] = 128134;
$b[5]['result_branch'] = 16;
$b[6]['result_branch'] = 128134;
$b[7]['result_branch'] = 12136;

$b[0]['text'] = "3213";
$b[1]['text'] = "qweq";
$b[2]['text'] = "wdas";
$b[3]['text'] = "d";
$b[4]['text'] = "cxzc";
$b[5]['text'] = "xzczx";
$b[6]['text'] = "czx";
$b[7]['text'] = "saed";
print_r($b);
print "<br>";
print "--------------------------------------------<br>";
print_r($b);
print "--------------------------------------------<br>";

foreach($a as $key1 => $subArray) {
foreach($subArray as $key2=>$ItemValue)
{
    $c[$key2][$key1] = $ItemValue; 
}
}
print "--------------------------------------------<br>";
print_r($c);
?>