2013-10-25 190 views
0

我有一個表單發佈4個數組,我需要合併並最終編寫成電子郵件。四個陣列:PHP:從數組創建數組

$quantityArray = $this->input->post('qty'); 
$dimensionArray = $this->input->post('dimension'); 
$thicknessArray = $this->input->post('thickness'); 
$descriptionArray = $this->input->post('description'); 

將具有相同的數組長度和每個索引將相關。如何結合4點陣列如

[0] 
    'qty' => '1', 
    'dimenesion => '2x2', 
    'thickness' => '2in', 
    'description' => 'this is the description' 
[1] 
    'qty' => '1', 
    'dimenesion => '2x2', 
    'thickness' => '2in', 
    'description' => 'this is the description' 

我已經試過array_combined,array_merged並不能得到,我尋找的結果。感謝您的幫助。

+1

一個簡單的循環可以做到這一點。 –

+0

順便說一句,你如何期待得到的數組?兩個陣列看起來都一樣 –

+0

對不起,只是複製並粘貼了示例結果。 – Bungdaddy

回答

2

如果你有相同的長度,在這裏這些陣列是示例代碼:

$resultArray = array(); 
foreach($quantityArray as $index => $qty) { 
    $resultArray[$index]['qty'] = $qty; 
    $resultArray[$index]['dimenesion'] = $dimensionArray[$index]; 
    $resultArray[$index]['thickness'] = $thicknessArray[$index]; 
    $resultArray[$index]['description'] = $descriptionArray [$index]; 
} 

print_r($resultArray); 
+0

很乾淨簡潔。感謝您的幫助! – Bungdaddy

+0

我很樂意提供幫助 – bksi

0

怎麼樣,如果總有那麼一些4個陣列的一個簡單的方法:

$quantityArray = $this->input->post('qty'); 
$dimensionArray = $this->input->post('dimension'); 
$thicknessArray = $this->input->post('thickness'); 
$descriptionArray = $this->input->post('description'); 

$combinedArray = [$quantityArray, $dimensionArray, $thicknessArray, $descriptionArray]; 

# old syntax: 
# $combinedArray = array($quantityArray, $dimensionArray, $thicknessArray, $descriptionArray); 
1

這也可能工作:

<?php 
//... 
$quantityArray = $this->input->post('qty'); 
$dimensionArray = $this->input->post('dimension'); 
$thicknessArray = $this->input->post('thickness'); 
$descriptionArray = $this->input->post('description'); 

// 
// combine them: 
// 
$combined = array(); 
$n = count($quantityArray); 
for($i = 0; $i < $n; $i++) 
{ 
    $combined[] = array(
    'qty' => $quantityArray[$i], 
    'dimenesion' => $dimensionArray[$i], 
    'thickness' => $thicknessArray[$i], 
    'description' => $descriptionArray[$i] 
); 
} 
// 
echo "<pre>"; 
print_r($combined); 
echo "</pre>"; 
?> 
1

如果我們假設我們有相同長度的陣列,這裏是我的代碼:

$quantityArray = array(1, 1, 5, 3); 
$dimensionArray = array("2x2", "3x3", "4x4", "2x2"); 
$thicknessArray = array("2in", "3in", "4in", "2in"); 
$descriptionArray = array("this is the description 1", "this is the description 2 ", "this is the description3 ", "this is the description4"); 

$myCombinArray = array(); 
foreach ($quantityArray as $idx => $val) { 
    $subArray = array (
      'qty' => $quantityArray [$idx], 
      'dimenesion' => $dimensionArray [$idx], 
      'thickness' => $thicknessArray [$idx], 
      'description' => $descriptionArray [$idx] 
    ); 
    array_push ($myCombinArray, $subArray); 
} 
print_r($myCombinArray);