holyredbeard
holyredbeard

Reputation: 21198

Creation of JSON object from arrays

I have a bunch of arrays and I want to create a JSON object from these.

Example arrays:

$brand = array('Kawasaki', 'Yamaha', 'Puch', 'Honda');
$colors = array('blue', 'red', 'yellow', 'blue');

The output I want:

$motorbikes = {
    motorbike1 {
        brand: 'Kawasaki',
        color: 'blue'
    },
    motorbike2 {
        brand: 'Yamaha',
        color: 'red'
    },
    motorbike3 {
        brand: 'Puch',
        color: 'yellow'
    },
    motorbike4 {
        brand: 'Honda',
        color: 'blue'
    }
}

What is the best and most elegant way of accomplish this?

Thanks!

Upvotes: 0

Views: 120

Answers (4)

MrCode
MrCode

Reputation: 64526

$brand = array('Kawasaki', 'Yamaha', 'Puch', 'Honda');
$colors = array('blue', 'red', 'yellow', 'blue');

$motorbikes = array();

for($i=0; $i<count($brand); $i++)
{
    $motorbikes['motorbike' . ($i+1)] = array(
        'brand' => $brand[$i],
        'color' => $colors[$i]
    );
}

echo json_encode($motorbikes);

Outputs (without the indentation)

{
    "motorbike1":{
        "brand":"Kawasaki",
        "color":"blue"
    },
    "motorbike2":{
        "brand":"Yamaha",
        "color":"red"
    },
    "motorbike3":{
        "brand":"Puch",
        "color":"yellow"
    },
    "motorbike4":{
        "brand":"Honda",
        "color":"blue"
    }
}

Codepad demo

Upvotes: 1

WhoaItsAFactorial
WhoaItsAFactorial

Reputation: 3558

I just threw this together, it isn't a perfect match to your desired output, but it should get you going in the direction you need to be in.

<?php

$brand = array('Kawasaki', 'Yamaha', 'Puch', 'Honda');
$colors = array('blue', 'red', 'yellow', 'blue');

$temp = array();
for ($i = 0; $i < count($brand); $i++)  {
    $temp["motorbike$i"]['brand'] = $brand[$i];
    $temp["motorbike$i"]['color'] = $colors[$i];
}

echo json_encode($temp);

?>

Upvotes: 2

user399666
user399666

Reputation: 19879

$motorbikes = array(
    'motorbike1' => array('brand' => 'Kawasaki', 'color' => 'Blue'),
    'motorbike2' => array('brand' => 'Yamaha', 'color' => 'Red'),
);

echo json_encode($motorbikes);

Upvotes: 1

wesside
wesside

Reputation: 5740

Easiest way is json_encode().

$brand_json = json_encode($brand);

http://php.net/manual/en/function.json-encode.php

Though, fix those arrays.:

$brand = array('Kawasaki', 'Yamaha', 'Puch', 'Honda');
$colors = array('blue', 'red', 'yellow', 'blue');

Upvotes: 3

Related Questions