从数组创建JSON对象

时间:2012-11-19 17:19:11

标签: php arrays json object

我有一堆数组,我想从这些数组创建一个JSON对象。

示例数组:

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

我想要的输出:

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

实现这一目标的最佳和最优雅的方法是什么?

谢谢!

3 个答案:

答案 0 :(得分:3)

最简单的方法是json_encode()

$brand_json = json_encode($brand);

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

但是,修复那些数组。:

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

答案 1 :(得分:1)

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

echo json_encode($motorbikes);

答案 2 :(得分:1)

$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);

输出(没有缩进)

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

Codepad demo