2012-07-19 62 views
2

我無法理解數組,我想知道如果有人可以幫助我在PHP中重新格式化現有的數組。從現有的數組中創建一個可行的數組在php

這是現有陣列:

Array 
(
[item] => Array 
(
    [0] => item listing 1 
    [1] => item listing 2 
) 

[description] => Array 
(
    [0] => item testing description 
    [1] => item testing description 
) 

[rate] => Array 
(
    [0] => 1.00 
    [1] => 2.00 
) 

[itemid] => Array 
(
    [0] => 1 
    [1] => 2 
) 
) 

我希望它看起來像這樣:

Array 
(
[0] => Array 
(
    [item] => item listing 1 
    [description] => item testing description 
    [rate] => 1.00 
    [itemid] => 1 
) 
[1] => Array 
(
    [item] => item listing 2 
    [description] => item testing description 
    [rate] => 2.00 
    [itemid] => 2 
) 

回答

3

如果所有的子陣列中的第一個的長度相同的這應該工作。

假設上面的第一個數組是在一個變量$inArray;新陣列是$outArray

$outArray = array(); 
$iLength = count($inArray['item']); 
for($i=0; $i<$iLength; $i++) { 
    $outArray[] = array(
     'item'  => $inArray['item'][$i], 
     'description' => $inArray['description'][$i], 
     'rate'  => $inArray['rate'][$i], 
     'itemid'  => $inArray['itemid'][$i]); 
} 
+0

+1看起來不錯:http://ideone.com/GAEhI – mellamokb 2012-07-19 17:12:23

+0

哎呀,這就是我在網頁上直接編輯的東西! – quickshiftin 2012-07-19 17:13:43

+1

感謝您的幫助,就像一個魅力! – neoszion 2012-07-19 17:38:57

2

好吧,如果你的主數組叫做$ master。然後,你會做這樣的事情:

$newArr = array(); 
foreach ($master as $key => $subArray) { 
    foreach ($subArray as $k2 => $value) { 
     $newArr[$k2][$key] = $value; 
    } 
} 
+1

+1作品! http://ideone.com/b9Gkb – mellamokb 2012-07-19 17:14:25

+0

什麼是$櫃檯? – 2012-07-19 17:16:01

+0

Woops當我想到需要跟蹤數組鍵時,我想到那裏,然後意識到我可以從$ k2獲得它:)。將其移出以消除混淆。 – aztechy 2012-07-19 17:18:26

0

合作,爲您具體的使用情況下(在空白的PHP的複製/粘貼):

$master = array( 
    'itemid' => array(1, 2), 
    'items' => array('item listing 1', 'item listing 2'), 
    'description' => array('item testing description', 'item testing description'), 
    'rate' => array(1.10, 2.10) 
); 

$newItems = array(); 
foreach($master['itemid'] as $index => $id) { 
    $newItem = array(
    'itemid' => $id, 
    'item' => $master['items'][$index], 
    'description' => $master['description'][$index], 
    'rate' => $master['rate'][$index], 
); 
    $newItems[] = $newItem; 
} 

echo '<pre>'; 
print_r($newItems); 
echo '</pre>'; 
+0

請注意,您還可以使用優秀網站http://ideone.com/測試代碼並鏈接到可運行示例。 – mellamokb 2012-07-19 17:14:59

+0

但輸出結果令人困惑,我更喜歡這個:http://writecodeonline.com/php/ :)(但是這不起「粘貼bin」的作用,但輸出更清晰。 – 2012-07-19 17:17:27

相關問題