如何在 PHP 中将数组元素转换为字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2131462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to cast array elements to strings in PHP?
提问by acme
If I have a array with objects:
如果我有一个包含对象的数组:
$a = array($objA, $objB);
(each object has a __toString()-method)
(每个对象都有一个__toString()-method)
How can I cast all array elements to string so that array $acontains no more objects but their string representation? Is there a one-liner or do I have to manually loop through the array?
如何将所有数组元素转换为字符串,以便该数组不$a包含更多对象,而是它们的字符串表示形式?是否有单行或我必须手动循环遍历数组?
回答by Alix Axel
回答by Ben Everard
Not tested, but something like this should do it?
没有经过测试,但这样的事情应该做吗?
foreach($a as $key => $value) {
$new_arr[$key]=$value->__toString();
}
$a=$new_arr;
回答by YOU
回答by Pekka
回答by Jan Jaso
Alix Axel has the nicest answer. You can also apply anything to the array though with array_map like...
Alix Axel 给出了最好的答案。您也可以使用 array_map 将任何内容应用于数组,例如...
//All your objects to string.
$a = array_map(function($o){return (string)$o;}, $a);
//All your objects to string with exclamation marks!!!
$a = array_map(function($o){return (string)$o."!!!";}, $a);
Enjoy
享受
回答by Martin Bean
Is there any reason why you can't do the following?
有什么理由不能执行以下操作吗?
$a = array(
(string) $objA,
(string) $objB,
);

