2

Something that bugs me for a long time:

I want to convert this Array:

// $article['Tags']
array(3) {
  [0] => array(2) {
    ["id"] => string(4) "1"
    ["tag"] => string(5) "tag1"
  },
  [1] => array(2) {
    ["id"] => string(4) "2"
    ["tag"] => string(5) "tag2"
  },
  [2] => array(2) {
    ["id"] => string(4) "3"
    ["tag"] => string(5) "tag3"
  },    
}

To this form:

// $extractedTags[]
array(3) {
  [0] => string(4) "tag1",
  [1] => string(4) "tag2",
  [2] => string(4) "tag3",
}

currently i am using this code:

$extractedTags = array();

foreach ($article['Tags'] as $tags) {
    $extractedTags[] = $tags['tag'];
}

Is there any more elegant way of doing this, maybe a php built-in function?

smoove
  • 3,920
  • 3
  • 25
  • 31
  • You could use `array_filter` using a callback function, but that's probably less elegant than the solution you have. I'd probably stick with what you've got. – Andy E Jun 01 '10 at 11:02
  • As my metrics on the duplicate http://stackoverflow.com/questions/2939189/php-multi-dimensional-array-manipulation/2939204#2939204 show the fastest method of doing what you want is the foreach. The `array_map` and `array_filter` have huge overhead as they need to call a user defined function for each element. – Matt S Jun 01 '10 at 14:17
  • I'm just adding this proposal for php 5.5: https://wiki.php.net/rfc/array_column - does exactly what i asked for. – smoove Jul 12 '12 at 12:53

1 Answers1

1

You can use array_map with anonymous functions:

// PHP 5.2
$extractedTags = array_map(create_function('$a', 'return $a["tag"];'), $article['Tags']);

// PHP 5.3
$extractedTags = array_map(function($a) { return $a['tag']; }, $article['Tags']);
Alexander Konstantinov
  • 5,406
  • 1
  • 26
  • 31
  • Thanks for your answer Alexander. Currently i still have to use PHP 5.2, and the create_function call makes it IMHO even less elegant. When i switch to PHP 5.3 i'll sure use the array_map method. – smoove Jun 01 '10 at 11:15
  • You can predefine the function and then pass a string as the first parameter in `array_map()`. Note though, array_map() is slow by comparison to a simple foreach. – Matt S Jun 01 '10 at 14:18