2016-03-10 100 views
-1

我有这个数组:如何组合阵列?

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) 

) 

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

+0

代码改变的关键在于它有没有尝试过任何东西 –

+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和文本的新细胞。

+0

你应该使用'count'。 'sizeof'可能会导致与其他语言中获得数组实际字节大小的函数混淆。 –

+0

是的,我明白这是'count'的别名,但我明白你的意思。我会改变这一点,以避免混淆。 – Matt

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); 
?>