如何推入多维数组的子数组?

时间:2011-08-29 18:19:34

标签: php arrays

我有两个数组

$brands = Array (1=>a, 2=>b);
$titles = Array (1=>d, 2=>e);

我想转换为一个二维数组

$both = Array ( [0] => Array ( [brand] => a, [title] => d ) [1] => Array ( [brand] => b, [title] = d ) );

我可以使用一对for循环来完成此操作,每个形式都是

$key_brand = 0;

foreach ($brands as $brand) {
    $both[$key_brand++]['brand'] = $brand;
}

但这看起来很笨拙,特别是如果我想合并这样的大量数组。我没有看到任何符合我想要的standard php function。有没有更好的方法呢?

2 个答案:

答案 0 :(得分:4)

我首先将所有输入信息放在一个数组中,以便您知道要循环的内容:

$old = array(
 'brands' => Array (1=>a, 2=>b),
 'titles' => Array (1=>d, 2=>e)
 // etc
);

然后做一个双循环:

$new = array();
foreach($old as $key => $value) 
{
  foreach ($value as $num_key => $content)
  {
    $new[$num_key][$key] = $content;
  }
}

另一个优点是您可以保留原始数组键。

答案 1 :(得分:2)

我刚才写的内容可能有所帮助。您可以成对指定参数:

<?php
$brands = array('Foo Global', 'Bar Global');
$titles = array('FooStar 1000', 'BarStar 1000');
$weights = array('400', '600');

function custom_array_merge() {
    $args = func_get_args();
    $arg_len = count($args);

    // Ensure there are no broken pairs. (Not a sophisticated check)
    if ($arg_len < 2 || $arg_len % 2 != 0)
        return FALSE;

    $output = array();

    for ($i = 1; $i <= $arg_len;) {
        $title = $args[$i-1];
        $values = $args[$i];
        foreach ($values AS $key => $value) {
            $output[$key][$title] = $value;
        }
        $i += 2;
    }

    return $output;
}

echo "<pre>";
print_r(custom_array_merge('brand', $brands, 'title', $titles, 'weight', $weights));
echo "</pre>";


示例输出:

Array
(
    [0] => Array
        (
            [brand] => Foo Global
            [title] => FooStar 1000
            [weight] => 400
        )

    [1] => Array
        (
            [brand] => Bar Global
            [title] => BarStar 1000
            [weight] => 600
        )

)