简体   繁体   English

将数组转换为php中的字符串

[英]Transform array to strings in php

I am trying to convert this array 我正在尝试转换此数组

array(3) {
  ["Men"]=>
  array(2) {
    ["Sport shoes"]=>
    array(1) {
      ["Football shoes"]=>
      array(0) {
      }
    }
    ["Winter shoes"]=>
    array(0) {
    }
  }
  ["Women"]=>
  array(0) {
  }
  ["Childrens"]=>
  array(0) {
  }
}

to this result 为了这个结果

Men
Men -> Sport shoes 
Men -> Sport Shoes -> Football shoes 
Men -> Winter shoes 
Women 
Childrens

I tried a lot of methods but without success. 我尝试了很多方法,但没有成功。 Can someone tell me how to do it. 有人可以告诉我该怎么做。

Thank you. 谢谢。

It can be done with simple recursive function like this: 可以使用简单的递归函数来完成,如下所示:

function printArray($array, $path = []) {
    if (!is_array($array) || count($array) < 1) {
        return;
    }
    foreach ($array as $k => $v) {
        if (count($path) > 0) {
            echo implode(' -> ', $path) . ' -> ';
        }
        echo $k . PHP_EOL;
        printArray($v, array_merge($path, [$k]));
    }
}

Live demo 现场演示

A possible recursive approach could work like this: 一种可能的递归方法可以像这样工作:

Starting with an empty string, iterate the array and append each key to the result. 从一个空字符串开始,迭代数组并将每个键附加到结果中。 Before continuing to the next iteration, if the value is not empty, append the result of the recursive call. 在继续进行下一个迭代之前,如果该值不为空,请附加递归调用的结果。 When you get to the end, you should have a string representing the entire structure. 到最后,您应该有一个代表整个结构的字符串。

function get_map(array $array, string $path = ''): string
{
    $result = '';
    foreach ($array as $key => $value) {
        $result .= "$path$key\n" . ($value ? get_map($value, "$path$key->") : '');
    }
    return $result;
}
echo get_map($array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM