How to “flatten” a multi-dimensional array to simple one in PHP?

前端 未结 23 2153
没有蜡笔的小新
没有蜡笔的小新 2020-11-22 01:03

It\'s probably beginner question but I\'m going through documentation for longer time already and I can\'t find any solution. I thought I could use implode for each dimensio

23条回答
  •  失恋的感觉
    2020-11-22 01:31

    If you're okay with loosing array keys, you may flatten a multi-dimensional array using a recursive closure as a callback that utilizes array_values(), making sure that this callback is a parameter for array_walk(), as follows.

    The one drawback of the preceding example is that it involves writing far more code than the following solution which uses array_walk_recursive() along with a simplified callback:

    See live code

    This example seems preferable to the previous one, hiding the details about how values are extracted from a multidimensional array. Surely, iteration occurs, but whether it entails recursion or control structure(s), you'll only know from perusing array.c. Since functional programming focuses on input and output rather than the minutiae of obtaining a result, surely one can remain unconcerned about how behind-the-scenes iteration occurs, that is until a perspective employer poses such a question.

提交回复
热议问题