我在__toString
方法中返回数组时遇到了困难。
这是我的代码。
public function __toString()
{
$this->_libraries();
$this->_sysConfig();
//print_r($this->version);
$version = implode("\n", $this->version);
echo $version;
return 'echo';//$version;
}
我一直在玩它但不管我做什么我仍然会得到这个错误
Notice: Array to string conversion in (...)
是否无法返回数组?
这是我试图内爆的数组
Array
(
[0] => Array
(
[version] => Array
(
[item] => Array
(
[0] => Array
(
[name] => cms
[version] => 1.0
)
[1] => Array
(
[name] => TinyMCE Jquery Package
[version] => 3.5
)
[2] => Array
(
[name] => Jquery
[version] => 1.7.2
)
)
)
)
)
答案 0 :(得分:2)
为什么要回显返回值然后返回PHP构造?
只需返回您的变量:
return $version;
<强>更新强>
我很确定你不能破坏多维数组。您需要编写一个自定义回调并调用array_walk才能正常工作。
答案 1 :(得分:1)
您不能在多维数组上使用implode
示例
$version = Array (
0 => Array (
'version' => Array (
'item' => Array (
0 => Array (
'name' => 'cms',
'version' => '1.0'
),
1 => Array (
'name' => 'TinyMCE Jquery Package',
'version' => '3.5'
),
2 => Array (
'name' => 'Jquery',
'version' => '1.7.2'
)
)
)
)
);
$version = implode ( $version, "\n" );
输出
Notice: Array to string conversion in xxxx
演示1
$version = multi_implode ( $version, "," );
输出
cms1.0 , TinyMCE Jquery Package3.5 , Jquery1.7.2
演示2
$version = multi_implode ( $version, " , " ," = " );
输出
cms = 1.0 , TinyMCE Jquery Package = 3.5 , Jquery = 1.7.2
使用的功能
function multi_implode($pieces, $glue, $glue2 = null) {
foreach ( $pieces as $piece ) {
if (is_array ( $piece )) {
$retVal [] = multi_implode ( $piece, $glue, $glue2 );
} else {
if ($glue2 == null) {
$retVal [] = $piece;
} else {
$retVal [] = implode ( $glue2, $pieces );
break;
}
}
}
return implode ( $glue, $retVal );
}