如何在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:10:12  来源:igfitidea点击:

How to cast array elements to strings in PHP?

phpstringarrayscasting

提问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

A one-liner:

单线:

$a = array_map('strval', $a);
// strval is a callback function

See PHP DOCS:

请参阅 PHP 文档:

array_map

数组映射

strval

斯特瓦尔

Enjoy! ;)

享受!;)

回答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

Are you looking for implode?

你在寻找内吗?

$array = array('lastname', 'email', 'phone');

$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

回答by Pekka

I can't test it right now, but can you check what happens when you implode()such an array? The _toString shouldbe invoked.

我现在不能测试它,但是你能检查一下当你有implode()这样一个数组时会发生什么吗?_toString应该被调用。

回答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,
);