在PHP中将数组转换为字符串 [英] convert array into string in PHP

查看:250
本文介绍了在PHP中将数组转换为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似PHP的数组:

i have an array like in PHP:

$a = array('110','111','121');

我想将其转换为:

$b = " '110' , '111' , '121' ";

PHP中有没有做过的功能?我知道这可以通过在数组上循环并在$ b中放入值来完成,但是我想要更少的代码解决方案.

is there any function in PHP that does it? i know it could be done with a loop on array and put value in $b, but i want a less more code solution.

谢谢.

推荐答案

您确实需要所有这些空格和引号吗?您仍然可以使用implode,尽管array_reduce可能更好

You do need all those spaces and quotes? You can still use implode, although array_reduce might be nicer

$a = array(1, 2, 3, 4);

$x = "'".implode("' , '", $a)."'";

array_reduce:

$x = array_reduce($a, function($b, $c){return ($b===null?'':$b.' , ')."'".$c."'";});

array_reduce的优点是,对于空数组(而不是''),您将获得NULL.请注意,您不能在5.3之前的php版本中使用此内联函数构造.您需要将回调函数设为单独的函数,并将其名称作为字符串传递给array_reduce.

Advantage of array_reduce, is that you will get NULL for an empty array, instead of ''. Note that you cannot use this inline function construct in php versions prior to 5.3. You'll need to make the callback a separate function and pass its name as a string to array_reduce.

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

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