views:

48

answers:

1

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?

+1  A: 

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
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.
smoove666
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