在PHP中内嵌关联数组 [英] Imploding an associative array in PHP

查看:85
本文介绍了在PHP中内嵌关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个数组:

$array = Array(
  'foo' => 5,
  'bar' => 12,
  'baz' => 8
);

我想在我的视图中像这样打印一行文本:

And I'd like to print a line of text in my view like this:

值是:foo(5),bar(12),baz(8)"

"The values are: foo (5), bar (12), baz (8)"

我能做的是这个

$list = Array();
foreach ($array as $key => $value) {
  $list[] = "$key ($value)";
}
echo 'The values are: '.implode(', ',$list);

但是我觉得应该有一个更简单的方法,而不必创建$list数组,这是一个额外的步骤.我一直在尝试array_maparray_walk,但是没有成功.

But I feel like there should be an easier way, without having to create the $list array as an extra step. I've been trying array_map and array_walk, but no success.

所以我的问题是:最好和最短的方法是什么?

So my question is: what's the best and shortest way of doing this?

推荐答案

array_map的问题是回调函数不接受键作为参数.您可以编写自己的函数来填补这里的空白:

The problem with array_map is that the callback function does not accept the key as an argument. You could write your own function to fill the gap here:

function array_map_assoc( $callback , $array ){
  $r = array();
  foreach ($array as $key=>$value)
    $r[$key] = $callback($key,$value);
  return $r;
}

现在您可以这样做:

echo implode(',',array_map_assoc(function($k,$v){return "$k ($v)";},$array));

这篇关于在PHP中内嵌关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆