PHP逐步介绍递归函数

时间:2018-12-05 09:31:07

标签: php arrays multidimensional-array

我有以下递归函数,该函数在嵌套数组中循环并复制json格式,我不能使用json_encode,以防万一有人认为为什么我不只是使用json_encode。到目前为止,该函数运行良好,但是从每个部分开始,我都需要删除最后一个逗号,并且理想情况下,我想创建正确的缩进以使其看起来更漂亮。

有什么想法可以做到这一点吗?谢谢

function walk_array($array) {
  foreach($array as $idx => $val) {
    if(is_array($val)) {
    echo '"'.$idx.'":{<br>  ';
     walk_array($val);
    echo "},<br>";
    } else {
    echo '"'.$idx.'":"'.$val.'",<br>';
    }
  }
}

*更新-要使用的示例数组*

$array = array
  ( 'brands' => array
    (
      'codes' => array('b' => "Apple", 'c' => 21, 'd' => 18),
      'items' => array('b' => "Google", 'c' => 22, 'd' => 19),
      'stock' => array('b' => "Samsung", 'c' => 23, 'd' => array('b' => "Samsung", 'c' => 23, 'd' => 20))
    )
  );

需要看起来像这样:

"brands":{

    "codes":{
        "b":"Apple",
        "c":"21",
        "d":"18"
    }

}

2 个答案:

答案 0 :(得分:0)

检查最后一个索引

function walk_array($array) {
  $lastIndex = count($array);
  $i = 0;
  foreach($array as $idx => $val) {
    if(is_array($val)) {
    echo '"'.$idx.'":{<br>  ';
     walk_array($val);
    if(++$i == $lastIndex )
     echo "}<br>";
    else
     echo "},<br>";
    } else {
   if(++$i == $lastIndex )
    echo '"'.$idx.'":"'.$val.'"<br>';    
   else
    echo '"'.$idx.'":"'.$val.'",<br>';
    }
  }
}

答案 1 :(得分:0)

这是一条声明:

$array = array
  ( 'brands' => array
    (
      'codes' => array('b' => "Apple", 'c' => 21, 'd' => 18),
      'items' => array('b' => "Google", 'c' => 22, 'd' => 19),
      'stock' => array('b' => "Samsung", 'c' => 23, 'd' => array('b' => "Samsung", 'c' => 23, 'd' => 20))
    )
  );

  function walk_array($array) {
      $numItems = count($array);
      $i = 0;
  foreach($array as $idx => $val) {
    if(is_array($val)) {
    echo '"'.$idx.'":{<br>  ';
     walk_array($val);
     $comma ="," ;
    if(++$i === $numItems) {$comma ="";}
    echo "}". $comma ."<br>";
    } else {
             $comma ="," ;
    if(++$i === $numItems) {$comma ="";}
    echo '"'.$idx.'":"'.$val.'",<br>';
    }
  }
}

walk_array($array);

输出:

"brands":{
"codes":{
"b":"Apple",
"c":"21",
"d":"18",
},
"items":{
"b":"Google",
"c":"22",
"d":"19",
},
"stock":{
"b":"Samsung",
"c":"23",
"d":{
"b":"Samsung",
"c":"23",
"d":"20",
}
}
}
this is what you need ???