如何从多维数组中复制单个数组?

时间:2013-04-02 11:56:27

标签: php arrays

我有一个多维数组,如下所示(PHP):

Array
(
    [144320] => Array
        (
            [3568728] => Array
                (
                    [30832] => 30832
                )

            [3568884] => Array
                (
                    [30827] => 30827
                    [30828] => 30828
                    [30830] => 30830
                    [30831] => 30831
                    [30832] => 30832
                    [30837] => 30837
                    [30838] => 30838
                    [30839] => 30839
                    [30826] => 30826
                    [30808] => 30808
                    [30806] => 30806
                    [30807] => 30807
                    [30698] => 30698
                    [30601] => 30601
                    [30697] => 30697
                )

        )

    [144330] => Array
        (
            [3568731] => Array
                (
                    [30827] => 30827
                    [30839] => 30839
                    [30838] => 30838
                    [30837] => 30837
                    [30832] => 30832
                    [30831] => 30831
                    [30828] => 30828
                    [30830] => 30830
                    [30826] => 30826
                    [30806] => 30806
                    [30808] => 30808
                    [30807] => 30807
                    [30698] => 30698
                    [30697] => 30697
                    [30601] => 30601
                )

        )

    [144218] => Array
        (
            [3568753] => Array
                (
                    [30808] => 30808
                )

        )

    [144216] => Array
        (
            [3568732] => Array
                (
                    [30808] => 30808
                )

        )

)

此数组由以下代码填充:

$sql = "SELECT * FROM `bf_alert_stack` WHERE `type` = 'immediately'  order by created desc";

$q   = db_query($sql);

$user_alerts = array();

  while ($row  = db_fetch_array($q)) 
{   
   $user_alerts [$row['uid']]    [$row['alert_id']]  [$row['nid']] = $row['nid'];
}

从上面的user_alerts数组中我想重新排列[$ row ['nid']]数组并重新排列我希望捕获[$ row ['nid']]数组并在将其捕获到另一个数组后我想重新-arrange $ row ['nid']数组我想将这个$ row ['nid']数组更新为原始的user_alerts数组。

我怎么能这样做?我没有在谷歌搜索任何这个,所以只是把它放在适当的地方。

1 个答案:

答案 0 :(得分:1)

您可以做的最好的事情是从查询中订购它,例如:

SELECT * FROM `bf_alert_stack` WHERE `type` = 'immediately' 
ORDER BY created desc, nid

但是如果您没有访问权限,或者由于其他原因需要原始排序,则需要在数组上递归迭代,并使用PHP ksort方法将最后一个分类级别重新分配给原始数组:

http://www.php.net/manual/en/function.ksort.php

foreach($user_alerts as $uid=>$user_alert) {
    foreach($alert as $alert_id=>$nids) {
        $user_alerts[$uid][$alert_id] = ksort($nids); 
    }   
}

希望它有所帮助!