社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

在使用php接收mysql结果后,但在编码为json之前,如何按类型对其进行分组?

div ern • 5 年前 • 1419 次点击  

我对php和sql非常陌生,一直在尝试如何将数据库结果转换成漂亮的json格式。我的主要问题是不能按数据类型对结果进行分组。

下面是表格、php代码和结果。

这是桌子的样子。

+------+--------------+-------------+-----------+
|  id  |  type        | color       |  cuteness |
+------+--------------+-------------+-----------+
|  1   |  fluffy      | tricolor    |  10       |
|  2   |  shorthair   | brown       |  5        |
|  3   |  angry       | white       |  9        |
|  4   |  fluffy      | black       |  8        |
|  5   |  lazy        | white       |  10       |
|  6   |  fighter     | white       |  6        |
|  7   |  fluffy      | black       |  8        |
|  8   |  shorthair   | tricolor    |  9        |
|  9   |  fluffy      | transparent |  7        |
| 10   |  shorthair   | neon        |  10       |
+------+--------------+-------------+-----------+

PHP:

$query = "SELECT * from 'kittens' order by date DESC";  
$sendoff = execute($query, 1); 


if (num_of_rows($sendoff) > 0) {
    //number of rows 
    $conta = num_of_rows($sendoff);

    // kittens array
    $kittens_arr=array();
    $kittens_arr["kittens_data"]=array();

    //displaynumberofkittens
    $kittens_arr["count"]= $conta;

    while ($kittensori = fetch_array($sendoff)){  

        //used for future separations
        $kitten = $kittensori['category'];

        extract($kittensori);

        $kittenslist=array(
            "type" => $kitten_type,
            "name" => $kitte_nname,
            "color" => $kitten_color,
            "cuteness" => $cuteness,
        );
        array_push($kittens_arr["kittens_data"], $kittenslist);
    }
}

这些是有效的结果,但我想看看是否可以按类型对结果进行分组。所以,如果小猫是毛茸茸的,那么它们应该按这个分组。

 {
 "kittens_data": [
  {
    "id": "1",
    "type": "fluffy",
    "color": "tricolor",
    "cuteness": "10",

  },
  {
    "id": "2",
    "type": "shorthair",
    "color": "brown",
    "cuteness": "5",

  }
]
}

下面是json。有可能吗?

 {
 "kittens_data": [
  {
    "type": "fluffy",
    "box": [{
       "id": "1",
       "color": "tricolor",
       "cuteness": "10"
    },
    {
       "id": "7",
       "color": "black",
       "cuteness": "8"
    }]   
  },
  {
    "type": "shorthair",
    "box": [{
       "id": "2",
       "color": "brown",
       "cuteness": "5"
    },
    {
       "id": "8",
       "color": "tricolor",
       "cuteness": "9"
    }]   
  }
]
}

任何帮助,或指向正确的方向都会大有帮助。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43424
 
1419 次点击  
文章 [ 2 ]  |  最新文章 5 年前