开发者

how to push onto a sub-array of a multidimensional array? [duplicate]

This question already has answers here: Is there a php function like python's zip? (14 answers) Closed 8 months ago.

I have two arrays

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

that I want to convert to one two-dimensional array

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

I can do this using开发者_Go百科 a pair of for loops, each of the form

$key_brand = 0;

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

but this seems clumsy, especially if I want to merge lots of arrays like this. I don't see any standard php function that does what I want. Is there a better way to do it?


I would start with putting all input information in an array so you know what to loop:

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

And then do a double loop:

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

An additional advantage is that you preserve your original array keys.


Here's something I just wrote that may help. You specify arguments in pairs:

<?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>";


Example output:

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

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

)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜