Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating an object with a key holding multiple array items

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My table looks like this.enter image description here

I get a very long arrays and not the comma separated list of models.

How can i fix this?.

>Solution :

The JSON you require is generated like this in php using nested arrays. The outer array is associative, like so.

$data_structure = [
     'Toyota' =>     ['Vitz', 'Corolla'],
     'Mazda' =>      ['Demio', 'SUV'],
     'Mitsubishi' => ['FH', 'FRR'],
];
$json = json_encode( (object) $data_structure );

That means you must, as you read your table, do two things:

  1. Create an entry in your associative array for each make of vehicle, but only if one doesn’t exist. The newly created entry should be an empty array.
  2. Append the model name to that array.

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 and model. You can adapt it to your actual data model.

$data_structure = [];   /* empty top-level array */
$query = $this->db->query('select make, model from key_value_pairs');
foreach ($query->result() as $row) {
    if (! array_key_exists ($row->make, $data_structure ) {
        /* create an entry for this row if none already exists */
        $data_structure[ $row->make ] = [];
    }
    /* append the model name to the array */
    $data_structure [ $row->make ] [] = $row->model;
}
$json = json_encode( (object) $data_structure;

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading