【问题标题】:Convert multidimensional array into single dimensional using values from child arrays使用子数组中的值将多维数组转换为一维数组
【发布时间】:2014-09-10 22:42:13
【问题描述】:

我有以下 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;
    }

这是一个简单的查询,但我不知道如何以我想要的方式检索数据,因为它返回的是一个多维数组。

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

我要做的是将每个数组中的值转换为键 => 值对。像这样:

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

我已经能够将其转换为一维数组,但格式不正确。

【问题讨论】:

    标签: php mysql arrays multidimensional-array


    【解决方案1】:

    试试这个:

    $new_array = array();
    foreach ($old_array as $elem) {
        $new_array[$elem["type"]] = $elem["total"];
    }
    
    var_dump($new_array); //for print the array
    

    【讨论】:

      【解决方案2】:

      对于 PHP >= 5.5,我给你array_column() 函数

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

      【讨论】:

      • 我很高兴知道这个功能。但它的问题是结果将是动态的,因此页面或类别可能并不总是存在。
      • 我在您修改后又试了一次。虽然它看起来应该可以工作,但它仍然产生了一个带有 2 个子数组的多维数组。将来会很有用,谢谢。
      猜你喜欢
      • 1970-01-01
      • 2023-03-26
      • 2019-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多