简体   繁体   中英

Remove parent array from multidimensional array in php

using php how to get array result into below way,

 Array
    (
        [3] => Array
            (
                [15] => 15
                [16] => 16
                [17] => 17
                [18] => 18
                [19] => 19
            )

    )

how to convert above array into below format,

 Array
        (
            [0] => 15
            [1] => 16
            [2] => 17
            [3] => 18
            [4] => 19
        )

array_values() is your friend;

Presuming your array exists in a variable called $array ;

$newArray = array_values($array[3]);

try this, if you have more than one sub-array, it will work.

$arr = array(3 =>
        array
          ( 
           15  => 15,
           16 => 16,    
           17    => 17,  
           18    => 18,  
           19    => 19
          )
        );
    $new = array();
        foreach ($arr as $v){
            $new = array_merge($new , array_values($v)) ;
        }
echo "<pre>"; print_r($new);

Working Demo

Have not tested it but should work as per your requirement.

<?php
$parent array = array(); // The array which you want to change
$result_array = array(); // The array that will hold the results
foreach( $parent_array as $child_array )
{
    if( is_array( $child_array ) )
    {
        foreach( $child_array as $element )
        {
            $result_array[] = $element
        }
    }
}
echo '<pre>';
print_r($result_array);
echo '</pre>';
?>

you should use RecursiveArrayIterator to remove parent array

$arr = new RecursiveIteratorIterator(new RecursiveArrayIterator($multidimensional_array));
$new_arr = iterator_to_array($arr, false);

it's pretty simple, as you can just assign the array holding variable to the values of one index …

<?php

/* build list */
for($i=15;$i<=19;$i++)
    $b[$i] = $i;
$a[3] = $b;

var_export($a);

/* make array smaller again */
$a = $a[3];

var_export($a);

/* reindexing, just values */
$a = array_values( $a );

var_export($a);

?>

the reindexing part is done by a build-in function, also have a look on php.net for the linked functions for arrays, you can do massive stuff simple with them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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