2012-07-19 40 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

相关问题