0

我有两个数组(下)。是否可以将它们转换为 json 字符串?

Array
        (
            [0] => size
            [1] => color
        )
Array
        (
            [0] => L
            [1] => Black
        )

输出结构应该是:

[
   {"name":"size","value":"L"},
   {"name":"color","value":"Black"}
]

谢谢!

4

5 回答 5

2

当然:

$array1 = array('size', 'color');
$array2 = array('L', 'Black');

$jsonArray = array();
foreach (array_combine( $array1, $array2 ) as $name => $value) {
    $jsonArray[] = array('name' => $name, 'value' => $value);
}

echo $json = json_encode($jsonArray);

这给你

[{"name":"size","value":"L"},{"name":"color","value":"Black"}]
于 2013-05-02T08:29:14.053 回答
0

我想你正在寻找这个:

$array1 = array('size', 'color');
$array2 = array('L', 'Black');
for($i=0;$i<sizeof($array1);$i++)
   {
    $array3[]=array($array1[$i]=>$array2[$i]);
    }
echo json_encode($array3);

?>

输出:

[{"size":"L"},{"color":"Black"}]

于 2014-04-26T18:40:28.020 回答
0

这应该工作:

$json = json_encode( array_combine( $array1, $array2 ) );
于 2013-05-02T08:24:13.950 回答
0

像这样的东西应该可以按照您的意愿工作:

<?php
    $keys = array("size", "color");
    $values = array("L", "Black");

    $array = array();
    foreach ($keys as $i => $key) {
        $array[] = array(
            "name" => $key,
            "value" => $values[$i]
        );
    }

    $json = json_encode($array);

    var_dump($json);

    //string(62) "[{"name":"size","value":"L"},{"name":"color","value":"Black"}]"
?>
于 2013-05-02T08:32:20.340 回答
0
    $array1 = array('size', 'color');
    $array2 = array('L', 'Black');

    $result = array_combine($array1 , $array2);
    $json = array();
    foreach($result as $key => $val){
     $json[] = array('name' => $key, 'value' => $value);
    }
    $json = json_encode($json);
于 2013-05-02T08:28:24.090 回答