drbmhd9583 2013-06-27 17:30
浏览 28
已采纳

PHP - 只合并数组的键?

Let's say I have a PHP array:

$array1 = array(
   'protein' => array('PROT', 100, 150),
   'fat'     => array('FAT',  100, 250),
   'carbs'   => arary('CARBS', 10, 20)
);

$array2 = array(
   'vitaminA' => array('vitA', 1, 2),
   'vitaminB' => array('vitB', 1, 2),
   'vitaminC' => arary('vitC', 1, 2)
);

Now I want a combined array of those nutrients (something like array_merge()), but I only need the keys, not the values themselves.

So either this:

$combined = array(
   'protein' => NULL,
   'fat'     => NULL,
   'carbs'   => NULL,
   'vitaminA'=> NULL,
   'vitaminB'=> NULL,
   'vitaminC'=> NULL
);

OR

$combined = array('protein', 'fat', 'carbs', 'vitaminA', 'vitaminB', 'vitaminC');

I can do this manually with a foreach loop, but I was hoping there's a function which would make this process fast and optimized.

  • 写回答

2条回答 默认 最新

  • dongyuan6949 2013-06-27 17:31
    关注

    Wouldn't this do the trick?

    $combined = array_merge(array_keys($array1), array_keys($array2));
    

    This would result in your option #2.

    I haven't done any benchmarks but I know that isset() is faster than in_array() in many cases; something tells me that it will be the same for isset() versus array_key_exists(). If it matters that much, you could try to use this:

    $combined = array_flip(array_merge(array_keys($array1), array_keys($array2)));
    

    Which would result in something like this:

    $combined = array(
        'protein' => 1,
        'fat'     => 2,
        'carbs'   => 3,
        'vitaminA'=> 4,
        'vitaminB'=> 5,
        'vitaminC'=> 6
    );
    

    That would allow you to use isset(), e.g. option #1.

    #edit I did some research on the performance of all three mentioned functions and most, if not all, case studies show that isset() is the fastest of all (1, 2); mainly because it is not actually a function but a language construct.

    However do note that we now use array_flip() to be able to use isset(), so we lose quite a few microseconds to flip the array; therefore the total execution time is only decreasing if (and only if) you use isset() quite often.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?