简体   繁体   中英

Transforming 2D array into 1D

This might seem obvious, but I have the following recursive function:

public static function dependencies($from_id) {
    $core = Core::getInstance();
    $query = $core->pdo->prepare("SELECT access_code FROM dependencies WHERE hierarchy=:id");
    $query->bindValue(":id",$from_id);
    $query->execute();
    while($data = $query->fetch()) {
        $codes[$data['access_code']] = self::dependencies($data['access_code']);
    }

    return $codes;

}

The output of this result:

Array
(
    [12] => 
    [17] => Array
        (
            [101] => 
            [104] => 
        )

    [18] => 
)

These values will always be unique and would like to transform this result into a single, one-dimensional array. What would be the most efficient way of doing this?

example: $array = array(12,17,101,104,18);

EDIT: $flat_codes = call_user_func_array('array_merge', $codes);

Sorry, I did not read the question carefully enough.

This should work:

<?php
function merge_keys ($in, &$out = array()) {
    foreach ($in as $k=>$val) {
        array_push ($out, $k);
        if (is_array ($val)) merge_keys ($val, $out);
    }
    return $out;
}

$input = Array
(
    "12" => "",
    "17" => Array
        (
            "101" => "",
            "104" => "",
        ),

    "18" => ""
);

$output = merge_keys ($input);
print_r($input); echo"<br />";
print_r($output);
?>

Passing the aray by reference is slightly more efficient than the other solution, which creates copies. However, on a small set of data the difference will hardly be noticeable.

Try recursive approach:

$codes = array(12 => '', 17 => Array( 101 => '', 104 => ''), 18 => '');
$res = flat_array_keys($codes);
echo '<pre>',print_r($res),'</pre>';
/* result is
Array
(
    [0] => 12
    [1] => 17
    [2] => 101
    [3] => 104
    [4] => 18
)*/

function flat_array_keys($arr) {
    $result = array();

    foreach ($arr as $k => $v) {
        $result[] = $k;
        if (is_array($v))
            $result = array_merge($result, flat_array_keys($v));
    }

    return $result;
}

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