开发者

elegant way to extract values from array

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[] = 开发者_StackOverflow$tags['tag'];
}

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


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']);
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜