2016-03-10 46 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); 
?>