这似乎很明显,但我有以下递归函数:
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;
}
此结果的输出:
Array
(
[12] =>
[17] => Array
(
[101] =>
[104] =>
)
[18] =>
)
这些值将始终是唯一的,并且希望将此结果转换为单个一维数组。这样做最有效的方法是什么?
示例:$array = array(12,17,101,104,18);
答案 0 :(得分:1)
编辑:
$ flat_codes = call_user_func_array('array_merge',$ codes);
抱歉,我没有仔细阅读这个问题。
这应该有效:
<?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);
?>
通过引用传递aray比创建副本的其他解决方案稍微有效。但是,在一小组数据上,这种差异几乎不会引起注意。
答案 1 :(得分:1)
尝试递归方法:
$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;
}