按值的值过滤数组,将其重新组织为每个键值的一个子数组

时间:2014-08-01 10:26:28

标签: php mysql arrays mysqli

我有一个PHP数组,我从MySQL数据库获得,但这是无关紧要的。示例PHP数组:

array ( 
    0 => array ( 
        'id' => 1, 
        'uid' => 0, 
        'file' => 'index.suf', 
        'field' => 'title', 
        'data' => 'www.webdevguru.co.uk', 
        'date' => '2014-03-22 15:39:14',
    ), 
    1 => array ( 
        'id' => 2, 
        'uid' => 0, 
        'file' => 'index.suf', 
        'field' => 'test1', 
        'data' => 'Well this is Awkward Mr Oliver Ingram.', 
        'date' => '2014-07-16 13:11:46', 
    ), 
    2 => array ( 
        'id' => 3, 
        'uid' => 0, 
        'file' => 'home.suf', 
        'field' => 'test2', 
        'data' => 'Value2.gif', 
        'date' => '2014-03-22 15:56:30', 
    ), 
);
//courtesy of `var_export()` so is valid PHP code.

由此我想分类如下:

array ( 
    'home.suf' => array ( 
        0 => array ( 
            'id' => 3, 
            'uid' => 0, 
            'file' => 'home.suf', 
            'field' => 'test2', 
            'data' => 'Value2.gif', 
            'date' => '2014-03-22 15:56:30', 
        ), 
    ), 
    'index.suf' => array ( 
        0 => array ( 
            'id' => 1, 
            'uid' => 0, 
            'file' => 'index.suf', 
            'field' => 'title', 
            'data' => 'www.webdevguru.co.uk', 
            'date' => '2014-03-22 15:39:14', 
        ), 
        1 => array ( 
            'id' => 2, 
            'uid' => 0, 
            'file' => 'index.suf', 
            'field' => 'test1', 
            'data' => 'Well this is Awkward Mr Oliver Ingram.', 
            'date' => '2014-07-16 13:11:46', 
        ), 
    ), 
);

它基本上按“文件”键下的值对它们进行分组,如果每个文件只有一个实例,那么完全简单的代码就是:

array_column($rows, null, 'file');

但不幸的是99.9%的时间不止一个,我完全相信这在PHP Foreach Loop很容易做到并且可以自己管理但是我想要尽可能多的不同方法来管理我想要的东西完成,所以我可以测试每个的边际表现,并选择最好的。在此之前,我每个文件都有一个迭代的SQL调用,所以它们就像$output[$file] = Return from MySQLi Method.一样,但是因为我试图提高脚本的速度,因为一些客户端可能有很多文件,这可能导致数百{{1}调用收集他们需要的所有信息,而不是我现在使用SELECT并同时收集它们,一个file IN()但是需要一些玩法才能使其格式正确。或者MySQLi中可能有某种方式以我想要的方式返回它们,让它们按MySQL Call分组。

1 个答案:

答案 0 :(得分:0)

我有两个功能性的foreach语句,致力于相当不同的方法;我仍然希望人们添加其他方法来实现我想要的输出。

foreach ($files as $file) {
    global $moo;
    $moo = $file;
    $method1[$file] = array_filter($rows, function($var) { global $moo; return $var['file']===$moo; });
}

foreach ($rows as $curr) {
    $method2[$curr['file']][] = $curr;
}

对小尺寸结果集进行一些测试后:

Method 0: 0.90606999397278
Method 1: 0.60176777839661
Method 2: 0.60173606872559

0 Being the Iterate through MySQL
1 Being the 1st Method Above
2 Being the 2nd Method Above