I have this format of json
{
"Toyota": ["Vitz", "Corolla"],
"Mazda": ["Demio", "SUV"],
"Mitsubishi": ["FH", "FRR"]
}
That i wish to return. In my code i have this
public function all_makes_and_models(){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
/**
{
"Toyota": ["Vitz", "Corolla"],
"Mazda": ["Demio", "SUV"],
"Mitsubishi": ["FH", "FRR"]
}
*/
$car_makes = array("Honda", "Mazda", "Nissan", "Subaru", "Toyota", "Acura", "Alfa Romeo", "Aston Martin", "Audi", "BAW", "Bentley", "BJC", "BMW", "Brabus", "Brilliance", "Buick", "Cadillac", "Changan", "Chery", "Chevrolet", "Chrysler", "Citroen", "Dacia", "Daewoo", "DAF", "Daihatsu", "Daimler", "Datsun", "Dodge", "Dongfeng", "Faw", "Ferrari", "Fiat", "Ford", "Foton", "GAC", "Geely", "Genesis", "Ginaf", "GMC", "Gonow", "Great Wall", "Haima", "Higer", "Hino", "Holden", "Hummer", "Hyundai", "Infiniti", "International", "Isuzu", "Iveco", "IVM", "JAC", "Jaguar", "Jeep", "Jetour", "JMC", "Joylong", "Kia", "King Long", "Lada", "Lamborghini", "Lancia", "Land Rover", "Lexus", "Lifan", "Lincoln", "Lotus", "Mahindra", "MAN", "Maserati", "McLaren", "Mercedes-Benz", "Mercury", "MG", "Mini", "Mitsubishi", "Mobius", "Morris", "Nord", "Oldsmobile", "Opel", "Peugeot", "Piaggio", "Polaris", "Pontiac", "Porsche", "Proton", "Renault", "Rolls-Royce", "Rover", "Saab", "Samsung", "Sany", "Saturn", "Scion", "Seat", "Secodi", "Simba", "Sinotruk", "Skoda", "SkyGo", "SMA", "Smart", "SsangYong", "Suzuki", "T King", "Tata", "Triumph", "TVS", "Vauxhall", "Vector", "Venturi", "Volkswagen", "Volvo", "Zotye", "ZX Auto");
$ca = [];
$keyvalues = array();
$car_make = 0;
foreach ($car_makes as $car_make) {
$query = $this->db->query("select valuex from key_value_pairs where parent='$car_make'");
$row = $query->row();
$rs = 0;
foreach ($query->result() as $row)
{
$rs = $row->valuex;
//array_push($ca,$rs);
$keyvalues[$rs] = $rs;
//echo $obj;
}
echo '<pre>';
//print_r($obj);
echo '</pre>';
}
My code loops through an array that holds all car makes and fetches model in a table that holds all models. I only provide the car make as parent in my query and all car models are returned.
I get a very long arrays and not the comma separated list of models.
How can i fix this?.
2
Answers
The JSON you require is generated like this in php using nested arrays. The outer array is associative, like so.
That means you must, as you read your table, do two things:
Your question is a bit confusing because your sample table doesn’t contain models like ‘Corolla’, so I’ll assume your table has columns called
make
andmodel
. You can adapt it to your actual data model.SQL deals in tables — rectangular arrangements of data. Your requirement is to transform that to a nested arrangement, and you have to do that task explicitly.
I haven’t confirmed it but try the above solution and let me know