简体   繁体   English

使用子数组中的值将多维数组转换为一维

[英]Convert multidimensional array into single dimensional using values from child arrays

I have the following PHP/MYSQL query: 我有以下PHP / MYSQL查询:

$sql = SELECT type, count(*) AS total FROM stats GROUP BY type
$this->sql = $sql;

function numObjects() {

        $stats = $this->conn->query($this->sql);
        while($stat_type = $stats->fetch_assoc()){
            $category[] = $stat_type;
        }
        return $category;
    }

It's a simple query, but I just can't figure out how to retrieve the data the way I want since it is returning a multidimensional array. 这是一个简单的查询,但是我无法弄清楚如何以我想要的方式检索数据,因为它正在返回多维数组。

array(2) { 
  [0]=> array(2) { 
    ["type"]=> string(4) "page" 
    ["total"]=> string(1) "1" 
   } 
  [1]=> array(2) { 
    ["type"]=> string(8) "category" 
    ["total"]=> string(1) "1" 
   } 
}

What I'm looking to do is convert the values from each array, into key => value pairs. 我想要做的是将每个数组中的值转换为键=>值对。 Like this: 像这样:

["page"]=> "1"
["category"]=> "1"

I've been able to convert it into a single dimensional array, but not in the correct format. 我已经能够将其转换为一维数组,但是格式不正确。

For PHP >= 5.5, I give you the array_column() function 对于PHP> = 5.5,我给你array_column()函数

$reformatted = array_column(
    $category,
    'total',
    'type'
);

try this: 尝试这个:

$new_array = array();
foreach ($old_array as $elem) {
    $new_array[$elem["type"]] = $elem["total"];
}

var_dump($new_array); //for print the array

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

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