如何将 php 数组格式化为所需的结果

我需要在图表中显示一些数据。基本上我有一个来自数据库的数组,它看起来像这样-


[

    [0] =>[


            [user_type] => 'Manager'

            [total_count] => 3


        ],



    [1] =>[


            [user_type] => 'Director'

            [total_count] => 2


        ]


]

还有一个user_type是Trainee 。如果用户Trainee有0 Total_count它不会出现在上面的数组中。所以我需要手动添加。所以首先将检查user_type3 个 user_types 中哪个不存在于上面的数组中。如果不存在则只需要添加total_count 0.


最后我想要的数组应该是这样的——


[

    ['labels'] =>['Manager','Director','Trainee],



    ['dataset'] => [ 3, 2, 0 ]


]

请注意这里,正确的顺序非常重要。所以在上面的数组中,Manager 有 3 个,Director 有 2 个,实习生有 0 个总数。


慕田峪4524236
浏览 215回答 3
3回答

慕少森

试试下面的代码也许它会有所帮助。/*using array column will get the result in&nbsp;Array ( [Manager] => 3 [Director] => 2 )*/$array_column = array_column($array, 'total_count', 'user_type');//Create new array like below$add_array = array('Manager'=>'0', 'Director'=>'0', 'Trainee'=>'0',);//using array_merge merge add_array and array_column$new_array = array_merge($add_array, $array_column);//using array_walk_recursive get the requird resultarray_walk_recursive($new_array, function($item, $key) use (&$final_array){&nbsp; &nbsp; $final_array['labels'][]=$key;&nbsp; &nbsp; $final_array['dataset'][]=$item;&nbsp; &nbsp; });echo "<pre>";print_r($final_array);?>案例 1- 如果受训者不在数组&nbsp;DEMO 中案例 2 - 如果 Manager 和 Director 都不在阵列&nbsp;DEMO 中案例 3- 如果主管不在 -演示

MMMHUHU

这是您可以使用带有 splat(...) 运算符的 array_combine 和 array_map 的脚本$arr = array_combine(['labels','dataset'],array_map(null, ...$arr));if(!in_array('Trainee',$arr['labels'])){&nbsp; &nbsp; array_push($arr['labels'],'Trainee');&nbsp; &nbsp; array_push($arr['dataset'],0);}print_r($arr);die;array_combine — 通过使用一个数组作为键和另一个作为其值的数组来创建一个数组注意:-在 array_map 中,NULL 可以作为值传递给回调以对多个数组执行 zip 操作。如果只提供了 array1,array_map() 将返回输入数组。总之就是执行数组操作的转置输出:-Array(&nbsp; &nbsp; [labels] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => Manager&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => Director&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [2] => Trainee&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; [dataset] => Array&nbsp; &nbsp; &nbsp; &nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [0] => 3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [1] => 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; [2] => 0&nbsp; &nbsp; &nbsp; &nbsp; ))

神不在的星期二

尝试这个$arr = array_combine(['labels','dataset'], array_map(null, $arr));制作一个将不存在的 user_type 添加到数组中的函数function setUserType($userType, $array) {&nbsp; &nbsp; if(!in_array($userType, $array['labels'])){&nbsp; &nbsp; &nbsp; &nbsp; array_push($array['labels'], $userType);&nbsp; &nbsp; &nbsp; &nbsp; array_push($array['dataset'], 0);&nbsp; &nbsp; }&nbsp; &nbsp; return $array;}通过任何用户类型调用函数,如“经理”、“实习生”、“导演”$arr = setUserType('Trainee', $arr);或者创建一个包含所有用户类型的数组并运行一个循环foreach(['Manager', 'Trainee', 'Director'] as $type) {&nbsp;$arr = setData($type, $arr);&nbsp; &nbsp;}打印并显示最终值print_r($arr);die();演示https://3v4l.org/UbiXn
打开App,查看更多内容
随时随地看视频慕课网APP