2016-02-17 78 views
-1

我有一個數組,看起來像這樣:合併兩個數組一起

array 
(
    [name] => name 
    [description] => description here 
    [first] => Array 
     (
      [0] => weight 
      [1] => height 
     ) 
    [second] => Array 
     (
      [0] => 20 kg 
      [1] => 50 cm 
     ) 
    [company_id] => 1 
    [category_id] => 7 
) 

什麼功能可以讓我將這些組合成的東西,看起來像下面?

array 
(
    [together] 
     (
      [0] => weight 20kg 
      [1] => height 50cm 
     ) 
) 
+0

是它始終只是要兩個指數?或者是否有* n *個索引,並且您希望將'first [n]'與'second [n]'(順便說一句,這非常接近您需要的實際語法...)。 – deceze

+0

它總是會以[first]和[second]出現,我需要將[first] [0]與[second] [0]相結合,依此類推。我知道如何用循環等來做到這一點......但我想看看是否有這樣的功能,我可以使用 –

+0

爲什麼不簡單地連接它們,當它總是相同? –

回答

3

更新

對於您需要使用循環,當前數組。

$first = $second = array(); 
foreach($yourArray as $key => $array) { 
    if(in_array($key, array('first', 'second')) { 
     $first[] = $array[0]; 
     $second[] = $array[1]; 
    } 
} 
$final['together'] = array($first, $second); 

根據第一陣列

你可以試試這個 -

$new = array(
    'together' => array(
     implode(' ', array_column($yourArray, 0)), // This would take out all the values in the sub arrays with index 0 and implode them with a blank space 
     implode(' ', array_column($yourArray, 1)), // Same as above with index 1 
    ) 
); 

array_column支持PHP> = 5.5

或者你可以嘗試 -

$first = $second = array(); 
foreach($yourArray as $array) { 
    $first[] = $array[0]; 
    $second[] = $array[1]; 
} 
$final['together'] = array($first, $second); 
+0

謝謝,這工作,但是你介意解釋第一個答案嗎? 我的數組上面顯示[first]和[second]實際上更像[name]和[description]。 那麼這怎麼知道我想結合哪些東西呢? –

+0

你可以顯示你的實際數組嗎? –

+0

當然我會更新我的問題 –

0

你也可以嘗試array_map如下

function merge($first,$second) 
 
{ 
 
\t return $first ." ".$second; 
 
} 
 
$combine = array_map('merge', $yourArray[0],$yourArray[1]);

+1

Downvote?它沒有幫助嗎? –