PHP 内爆多维数组 - 无法访问数组中的数组

PHP implode multidimensional array - unable to access an array within an array

正在尝试按如下方式分解多维数组:

"data": [
        {
            "1": "",
            "2": "211",
            "3": 0,
            "x": [
                2661.898,
                0
            ],
            "4": 2662.138,
            "5": 0,
            "y": [
                166,
                0
            ]}
    ]

PHP代码

$json =  file_get_contents( 'myjson' );
$implode = array();
$multiple = json_decode( $json, true );
    foreach ( $multiple[ "data" ] as $key => $single)

        $implode[] = is_array($single) ? implode( ', ', $single) : $single ;

echo implode( '<br>', $implode );

目前我得到这样的结果,因为我无法访问嵌套数组。

0, 211, 0, Array, 2662.138, 0, Array

我做错了什么以及如何访问这些嵌套数组?我希望代码只进入任何嵌套数组,而不必按名称调用它们,所以 x[0]、y[1] 等

下面的代码应该可以解决问题。

$s = '
{"data": [
        {
            "1": "",
            "2": "211",
            "3": 0,
            "x": [
                2661.898,
                0
            ],
            "4": 2662.138,
            "5": 0,
            "y": [
                166,
                0
            ]}
    ]}';

$aData   = json_decode($s, true);
$implode = array();

foreach ($aData["data"] as $pos => &$v) {

    foreach ($v as $pos2 => $v2) {
        if(is_array($v2)){
            $aData["data"][$pos][$pos2] = implode(',', $v2);
        }
    }

    $implode[] = implode(',', $v);
}

var_dump($implode);

生产

array(7) {
  [1]=>
  string(0) ""
  [2]=>
  string(3) "211"
  [3]=>
  int(0)
  ["x"]=>
  string(10) "2661.898,0"
  [4]=>
  float(2662.138)
  [5]=>
  int(0)
  ["y"]=>
  string(5) "166,0"
}

你可以使用递归:

<?php
$json = "{\n\"data\": [\n        {\n            \"1\": \"\",\n            \"2\": \"211\",\n            \"3\": 0,\n            \"x\": [\n                2661.898,\n                0\n            ],\n            \"4\": 2662.138,\n            \"5\": 0,\n            \"y\": [\n                166,\n                0\n            ]}\n    ]\n}";


$multiple = json_decode( $json, true );



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

    // Recursively iterates array and adds key/value to glued string
    array_walk_recursive($array, function($value, $key) use ($glue, $include_keys, &$glued_string)
    {
        $include_keys and $glued_string .= $key.$glue;
        $glued_string .= $value.$glue;
    });

    // Removes last $glue from string
    strlen($glue) > 0 and $glued_string = substr($glued_string, 0, -strlen($glue));

    // Trim ALL whitespace
    $trim_all and $glued_string = preg_replace("/(\s)/ixsm", '', $glued_string);

    return (string) $glued_string;
}
echo recursive_implode($multiple['data']);

输出:

,211,0,2661.898,0,2662.138,0,166,0