如何将3D矩阵转换为字符串?

时间:2018-06-24 01:20:30

标签: php

$data = [[[1,2],[3,4]], [[5,6], [7,8]]] 
/* An array inside an array inside an array, a 3d matrix  */
echo implode(" ", $data);

返回:

Notice: Array to string conversion in C:\xampp\htdocs\dad_app\test.php on line 2

Notice: Array to string conversion in C:\xampp\htdocs\dad_app\test.php on line 2

1 个答案:

答案 0 :(得分:0)

您可以使用递归进行此操作,因为您可以使用array_walk_recursive

<?php
$data = [[[1,2],[3,4]], [[5,6], [7,8]]] ;
/* An array inside an array inside an array, a 3d matrix  */

function recursive_implode(array $array, $glue = ',', $include_keys = false, $trim_all = true)
{
    $glueStr = '';

    array_walk_recursive($array, function($value, $key) use ($glue, $include_keys, &$glueStr)
    {
        $include_keys and $glueStr .= $key.$glue;
        $glueStr .= $value.$glue;
    });

    strlen($glue) > 0 and $glueStr = substr($glueStr, 0, -strlen($glue));

    $trim_all and $glueStr = preg_replace("/(\s)/ixsm", '', $glueStr);
    return (string) $glueStr;
}


echo recursive_implode($data);
?>