Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 内爆数组值?_Php_Loops_Multidimensional Array_Implode - Fatal编程技术网

Php 内爆数组值?

Php 内爆数组值?,php,loops,multidimensional-array,implode,Php,Loops,Multidimensional Array,Implode,我有一个这样的数组: Array ( [0] => Array ( [name] => Something ) [1] => Array ( [name] => Something else ) [2] => Array ( [name] => Something else....

我有一个这样的数组:

Array
(
    [0] => Array
        (
            [name] => Something
        )

    [1] => Array
        (
            [name] => Something else
        )

    [2] => Array
        (
            [name] => Something else....
        )
)
echo implode(', ', $array[index]['name']) // result: Something, Something else, Something else...
foreach ($array as  $key => $val) {
    $string .= ', ' . $val;
}
$string = substr($string, 0, -2); // Needed to cut of the last ', '
是否有一种简单的方法将值内插到字符串中,如下所示:

Array
(
    [0] => Array
        (
            [name] => Something
        )

    [1] => Array
        (
            [name] => Something else
        )

    [2] => Array
        (
            [name] => Something else....
        )
)
echo implode(', ', $array[index]['name']) // result: Something, Something else, Something else...
foreach ($array as  $key => $val) {
    $string .= ', ' . $val;
}
$string = substr($string, 0, -2); // Needed to cut of the last ', '
不使用使用循环浓缩值,如下所示:

Array
(
    [0] => Array
        (
            [name] => Something
        )

    [1] => Array
        (
            [name] => Something else
        )

    [2] => Array
        (
            [name] => Something else....
        )
)
echo implode(', ', $array[index]['name']) // result: Something, Something else, Something else...
foreach ($array as  $key => $val) {
    $string .= ', ' . $val;
}
$string = substr($string, 0, -2); // Needed to cut of the last ', '

您可以使用一个常见的
array\u-map()
技巧“展平”多维数组,然后
inflade()
展平”结果,但在内部,当您调用
array\u-map()
时,PHP仍然在数组中循环


最简单的方法是,当内部数组中只有一个项时:

$values = array_map('array_pop', $array);
$imploded = implode(',', $values);
在PHP 5中>=5.5.0

implode(', ', array_column($array, 'name'))

是的,但是PHP做得更快。谢谢。这最好使用array_pop()。如果为第二层阵列提供了额外的密钥,则不能保证“name”密钥将是堆栈中的第一个密钥。防御性编程FTW。另一方面,如果您对在名称空间中创建新函数持怀疑态度,请使用闭包或create_函数。回声内爆(“,”,数组映射(创建函数(“$a”,“返回$a[“名称”];”),$array));关于你的第二条评论,你有一个很好的观点,但在这种情况下,单打解决方案就可以了。是的,我对为这种用法创建函数有点怀疑。你看,我正处于学习OOP的中间,所以我对何时何地使用“正常”函数感到困惑。你最后的评论解决了这个问题。我希望我能接受两篇帖子。@Rafe Ketterr:是的,但它只适用于一维数组。我得到的数组_pop()期望参数1是数组,字符串given@DhanuK我看不到代码,但我可以大胆猜测,您有一个包含项的数组,而不是一个包含项的数组。