PHP数组与不同类型的键合并

时间:2018-08-27 20:11:02

标签: php mysql yii yii2

是否有任何方法可以将数组键与唯一名称合并,所以我可以获得具有其类型和值的唯一键。我正在使用yii2和mysql

我在yii2中使用以下SQL查询:

MyModel.objects.annotate(name_lower=Lower('name')).filter(name_lower__in=[name.lower() for name in name_list])

,SQL查询的输出为

$data= $query->SELECT(["sum(no_of_pages) as pages_coded",'assigned_to','type_of_request','concat(firstname," ",lastname) as userfullname'])
->from('task')
->leftJoin('user','user.username = task.assigned_to')
->andWhere("sdlc_phase='Resolved'")
->orWhere("sdlc_phase='Semi_Resolved'");
$query->groupby(['assigned_to', 'type_of_request']);
//$query->->addGroupBy('assigned_to');
$query->orderby(['assigned_to'=>SORT_ASC]);
$data = $query->all();

但是我想要生成这样的输出,无论如何要得到这个

Array
(
    [0] => Array
        (
            [pages_coded] => 5
            [type_of_request] => Collector Tweak
            [userfullname] => Sam
        )
    [1] => Array
        (
            [pages_coded] => 5
            [type_of_request] => Collector Code
            [userfullname] => John
        )
    [2] => Array
        (
            [pages_coded] => 42
            [type_of_request] => Collector Tweak
            [userfullname] => John
        )
    [3] => Array
        (
            [pages_coded] => 37
            [type_of_request] => Clinical Tweak
            [userfullname] => Dona
        )
    [4] => Array
        (
            [pages_coded] => 35
            [type_of_request] => Collector Code
            [userfullname] => Dona
        )
    [5] => Array
        (
            [pages_coded] => 7
            [type_of_request] => Clinical Code
            [userfullname] => Ricky
        )
    [6] => Array
        (
            [pages_coded] => 50
            [type_of_request] => Clinical Tweak
            [userfullname] => Ricky
        )
    [7] => Array
        (
            [pages_coded] => 4
            [type_of_request] => Collector Code
            [userfullname] => Ricky
        )
    [8] => Array
        (
            [pages_coded] => 17
            [type_of_request] => Collector Tweak
            [userfullname] => Ricky
        )
)

帮助我解决此问题。

1 个答案:

答案 0 :(得分:4)

对于您想要的输出,您将不得不遍历创建另一个数组的结果。

$output = array();
foreach ($data as $row) {
    $output[$row['userfullname']][$row['type_of_request']] = $row['pages_coded'];
}

像这样,您将得到类似以下的数组:

$output = array(
    'Sam' => array(
        'Collector Tweak' => 5
    ),
);

并且既然您显然希望其他列如果找不到则用0填充:

$categories = array(
    'Clinical Code' => 0,
    'Clinical Tweak' => 0,
    'Collector Code' => 0,
    'Collector Tweak' => 0,
);
foreach ($output as &$outputItem) {
    $outputItem = array_merge($categories, $outputItem);
}

根据定义,这更容易跟踪索引及其各自的值。

在这里测试:https://3v4l.org/0k40Q