PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 22, 2022

[FIXED] How to turn a php array of unlimited(unknown) depth into a single array?

 July 22, 2022     php, php-5.3, php-5.4     No comments   

Issue

Array
(
    [72] => Array
        (
            [id] => 70
            [login] => test100
            [parent_id] => 1
            [type_id] => 1
            [position] => 1
            [user_id] => 72
            [children] => Array
                (
                )

        )

    [73] => Array
        (
            [id] => 72
            [login] => test101
            [parent_id] => 1
            [type_id] => 1
            [position] => 2
            [user_id] => 73
            [children] => Array
                (
                    [74] => Array
                        (
                            [id] => 74
                            [login] => test105
                            [parent_id] => 72
                            [type_id] => 1
                            [position] => 1
                            [user_id] => 74
                            [children] => Array
                                (
                                )

                        )

                )

        )

)

I have this array for example, but the depth can be unlimited, how to convert an ulimited or unknown of depth multidimensional array to single array?


Solution

<?php

$aNonFlat = array(
1,
2,
array(
    3,
    4,
    5,
    array(
        6,
        7
    ),
    8,
    9,
),
10,
11
);

$objTmp = (object) array('aFlat' => array());

array_walk_recursive($aNonFlat, create_function('&$v, $k, &$t', '$t->aFlat[] = $v;'),     $objTmp);

var_dump($objTmp->aFlat);

?>


Answered By - Dima
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing