簡體   English   中英

PHP:從數組創建數組

[英]PHP: create array from arrays

我有一個表單,該表單發布了4個需要組合並最終組成電子郵件的數組。 四個數組:

$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,但無法獲得所需的結果。 感謝您的幫助。

如果這些數組的長度相同,則為示例代碼:

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

這也可能起作用:

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

如果我們假設這些數組的長度相同,這是我的代碼:

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

如果總是有這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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM