什么查询会得到我这个结果? JSON和PHP

时间:2015-02-25 13:00:58

标签: php jquery mysql arrays json

{
    "cars": {
        "toyota": [
            {"model":"*****", "doors":"*","color":"*****"},
            {"model":"*****", "doors":"*","color":"*****"}
                  ],
        "Ford": [
            {"model":"*****", "doors":"*","color":"*****"},
            {"model":"*****", "doors":"*","color":"*****"}
        ]
    }
}

什么查询会给我以下结果?

它是一个JSON对象(汽车),它包含多个阵列,每个阵列用于不同型号的汽车。在每个阵列中将是其他类型的数据,例如门,颜色,年......等等。

我试过这段代码:

<?php 

require 'conn_pdo.php';

$conn -> setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC); 

$sql = "select * from test_cars where cars in (select cars from test_cars GROUP BY cars) ORDER BY RAND()";

$stmt = $conn -> prepare($sql);
$stmt -> execute();
$row = $stmt -> fetchAll();
$json['cars'] = $row;
echo json_encode($json);

?>

但结果不是我希望

{ "cars": 
         [ {"model":"*****", "doors":*","color":*****"},  
           {"model":"*****","doors":"*","color":*****"} ,
           {"model":"*****", "doors":"*","color":*****"}, 
           {"model":"*****", "doors":"*","color":*****"},
           .......
         ] 
}

我有汽车对象,包含一个阵列适用于所有不同型号的汽车!!

1 个答案:

答案 0 :(得分:0)

这是一种方法。我已经删除了GROUP BY方法,因为问题中的方法没有正确使用它 - 它使用IN查询抛出了分组。无论如何,我觉得用PHP做起来很容易。

// It would be good to check to ensure you have a valid connection,
// and that the prepare/execute calls are successful
$sql = "SELECT * from test_cars";
$stmt = $conn->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll();

$out = [];
foreach ($rows as $row)
{
    // Let's process by brand (since you have not shown your
    // schema, you will need to adjust column names to suit)
    $brand = $row['brand'];

    // Get other data
    $model = $row['model'];
    $doors = $row['doors'];
    $colour = $row['colour'];

    // Check to ensure the brand is an array, so that we don't
    // get an error when we push
    if (!isset($out[$brand]))
    {
        $out[$brand] = [];
    }

    // Now push the data on to the end (using [])
    $out[$brand][] = [
        'model' => $model,
        'doors' => $doors,
        'colour' => $colour,
    ];
}

$json['cars'] = $out;
echo json_encode($json);

这是未经测试的,但应该给你一般的想法。您应该期望必须稍微调整一下,就像Stack Overflow上的所有答案一样。我已经使用了新的数组语法(从PHP 5.4开始),但如果你将它交换为array(),它将适用于早期版本。