简体   繁体   English

在PHP中转换数组时遇到麻烦

[英]having trouble in transforming a array in php

i have this array 我有这个数组

[ 
    [[222] => 1 [333] => 2 [444] => 0],
    [[222] => 0 [333] => 2 [444] => 1],
    [[222] => 1 [333] => 2 [444] => 0]
]

where [222], [333], [444] are student ids 其中[222],[333],[444]是学生ID
and 0 means absent 1 means Present 2 means Leave 0表示缺席1表示出席2表示离开

i want the output will 我想要输出

[ 'student_id' => '222'
  'present' => 2 /* total present*/
  'absent' => 1  /* total absent*/
  'leave'  => 0 /* total leave*/
],
[ 'student_id' => '333'
  'present' => 0 /* total present*/
  'absent' => 0  /* total absent*/
  'leave'  => 3 /* total leave*/
],

etc. 等等

please give me some soluation in php code 请给我一些PHP代码的解决方案

This does exactly what you want, but this site is not a coding service, so i really think you should take the time to understand how i did, and next time try something and share it on your post: 这确实可以满足您的要求,但是此站点不是编码服务,因此我真的认为您应该花时间了解我的工作方式,然后下次尝试一些操作并在您的帖子上分享:

$array = [
    [
        "222" => 1, 
        "333" => 2,
        "444" => 0
    ],
    [
        "222" => 0, 
        "333" => 2,
        "444" => 1
    ],
    [
        "222" => 1, 
        "333" => 2,
        "444" => 0
    ]
];
$results = [];
foreach($array as $k=>$v){
    foreach($v as $id=>$value){
        if(!isset($results[$id])){
            $results[$id] = [
                'student_id' => $id,
                'present' => 0,
                'absent' => 0,  
                'leave'  => 0
            ];
        }
        if($value == 0){
            $results[$id]['absent']++;
        }
        if($value == 1){
            $results[$id]['present']++;
        }
        if($value == 2){
            $results[$id]['leave']++;
        }
    }
}
$results = array_values($results);
print_r($results);

This looks like JSON value with there respective keys. 这看起来像带有相应键的JSON值。 You may do that firstly you can arrange these values in PHP ARRAY using foreach then convert that array in JSON. 您可能首先要做的是,可以使用foreach在PHP ARRAY中安排这些值,然后在JSON中转换该数组。

foreach looping is the best way to access each key/value pair from an array. foreach循环是从数组访问每个键/值对的最佳方法。

foreach($featured as $key => $value){...}

The $key => $value in the foreach loop refers to the key-value pairs in associative arrays, where the key serves as the index to determine the value instead of a number like 0,1,2,... In PHP, associative arrays look like this foreach循环中的$key => $value引用关联数组中的键/值对,其中键用作确定值的索引,而不是像0,1,2,...这样的数字。在PHP中,关联数组如下所示

$featured = array('student_id' => '111', 'present' => '2', etc.);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM