Easiest way to remove Keys from a 2D Array?

Posted by dbemerlin on Stack Overflow See other posts from Stack Overflow or by dbemerlin
Published on 2010-04-06T12:53:38Z Indexed on 2010/04/06 13:33 UTC
Read the original article Hit count: 227

Filed under:
|
|

Hi,
I have an Array that looks like this:

array(
  0 => array(
    'key1' => 'a',
    'key2' => 'b',
    'key3' => 'c'
  ),
  1 => array(
    'key1' => 'c',
    'key2' => 'b',
    'key3' => 'a'
  ),
  ...
)

I need a function to get an array containing just a (variable) number of keys, i.e. reduce_array(array('key1', 'key3')); should return:

array(
  0 => array(
    'key1' => 'a',
    'key3' => 'c'
  ),
  1 => array(
    'key1' => 'c',
    'key3' => 'a'
  ),
  ...
)

What is the easiest way to do this? If possible without any additional helper function like array_filter or array_map as my coworkers already complain about me using too many functions.

The source array will always have the given keys so it's not required to check for existance.

Bonus points if the values are unique (the keys will always be related to each other, meaning that if key1 has value a then the other key(s) will always have value b).

My current solution which works but is quite clumsy (even the name is horrible but can't find a better one):

function get_unique_values_from_array_by_keys(array $array, array $keys)
{
        $result = array();
        $found = array();

        if (count($keys) > 0)
        {
                foreach ($array as $item)
                {
                        if (in_array($item[$keys[0]], $found)) continue;
                        array_push($found, $item[$keys[0]]);
                        $result_item = array();
                        foreach ($keys as $key)
                        {
                                $result_item[$key] = $item[$key];
                        }
                        array_push($result, $result_item);
                }
        }
        return $result;
}

Addition:
PHP Version is 5.1.6.

© Stack Overflow or respective owner

Related posts about php

Related posts about array