2015-09-07 36 views
1

我有2個數組:數組合並:使用foreach?

$im=explode(",", $data['products']); 
$imi=explode(",", $data['period']); 

其相關聯:

$data['products'] = balon,globo,sesta 
$data['period'] = 1,1,2 

所以當我合併的結果,它是:

Array ([0] => DS Basic [1] => DS Pro [2] => DS Start [3] => 1 [4] => 1 [5] => 2) 

的問題是,我需要它是像這樣關聯:

DS Basic = 1 , DS Pro = 1 , DS Start = 2 

我正在使用array_merge($im,$imi)

我該如何使用foreach來做到這一點? 我想這樣的:

Array ([0] => DS Basic [1] => DS Pro [2] => DS Start) 
Array ([0] => 1 [1] => 1 [2] => 2) 

所以,當我使用它,它可以像

using foreach 

DS basic has a period of 1 

DS pro has a period of 1 

DS start has a period of 2 
+0

你能'的print_r( $ IM)'? – aldrin27

回答

1

你需要的是組合,而不是合併)具有看看PHP對array_combine手冊。

請不考慮你的期望的結果保存一組數據作爲鍵(在你的榜樣產品陣列值),你是不是想有重複值,否則你將失去他們

+1

那是因爲我在尋找謝謝它的工作 –

+0

你最不歡迎:) – Ali

1

您可以修復合併的結果如下:

$merged = array_merge($im,$imi); 
$period = array(); 
// Loop through the merged items 
foreach ($merged as $k=>$v) { 
    // Check if the value is an integer 
    if ((int)$v) { 
    // Move this value to the period array 
    $period[] = $v; 
    // Remove it from the merged array 
    unset($merged[$k]); 
    } 
} 
// Reindex the merged array to revalue the keys 
$merged = array_values($merged); 
// Test the output 
echo '<h1>Merged Array:</h1>'; 
echo '<pre>'; 
echo print_r($merged); 
echo '</pre>'; 
echo '<h1>Excess Array:</h1>'; 
echo '<pre>'; 
echo print_r($period); 
echo '</pre>'; 
exit; 
1
$merged = array(); 
if (count($im) != count($imi)) { 
    print "custom merging is not possible..."; 
} 
else { 
    for($i=0 ; $i<count($im) ; $i++) { 
     $merged[$im[$i]] = $imi[$i]; 
    } 
} 
1

你可以做foreach

$newArr = []; 
    foreach($im $key => $val) 
    { 
     $newArr[] = [$val[0] => $imi[$key][0], $val[1] => $imi[$key][1], $val[2] => $imi[$key][2]]; 
    } 
    print_r($newArr); 

或者結合起來:

$result = array_combine($im, $imi);