這是我更可重複使用的決定之前,已經使用的情況下,要添加例如,不僅姓名,年齡,但後來其他電子郵件或東西。
在解釋註釋的下方發佈代碼。
<?php
// Array containing names
$namesArr = array(
'Peter',
'Josh',
'Jasper'
);
// Array containing ages
$agesArr = array(
18,
19,
25
);
$arrayDesign = array(
'name' => $namesArr,
'age' => $agesArr
);
/**
* Combines given array design into one grouped by keys.
* Example Input:
* $design => array(
* 'name' => array('Name1', 'Name2'),
* 'age' => array(10, 20)
* );
* Example Output:
* $output => array(
* 0 => array(
* 'name' => 'Name1',
* 'age' => 10
* ),
* 1 => array(
* 'name' => 'Name2',
* 'age' => 20
* )
* );
*
* @param Array $arrayDesign
*
* @return Array combined array
*/
function combineArraysByKeys($arrayDesign) {
// Holds results
$results = array();
// Get size of first element from the design, so we'll know the size of rest elements.
$designElementSize = count($arrayDesign[array_keys($arrayDesign)[0]]);
// Count from-to elements
for($c = 0; $c < $designElementSize; $c++) {
// Define array as part of results to be added after population
$arrayPart = array();
// Loop thru all keys and get values
foreach(array_keys($arrayDesign) as $key) {
// Assign value to key
$arrayPart[$key] = $arrayDesign[$key][$c];
}
// Add to results array
$results[] = $arrayPart;
}
return $results;
}
$result = combineArraysByKeys($arrayDesign);
echo "<PRE>";
print_r($result);
die();
foreach或for循環可能是最好的選擇。 – aynber
當然,我做了一個努力,我已經解釋了我所嘗試過的。爲什麼你認爲我沒有理由不投票給我? :( – user3628807
好的,我用for循環做了。感謝@aynber的頭像! – user3628807