dougou7008
dougou7008
2013-05-02 08:19

php数组合并并转换为json

已采纳

I have two arrays (below). Is it possible to convert them into json string?

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

Output structure should be:

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

Thanks!

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

5条回答

  • duanlangwen9597 duanlangwen9597 8年前

    Sure:

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

    This gives you

    [{"name":"size","value":"L"},{"name":"color","value":"Black"}]
    
    点赞 评论 复制链接分享
  • dongwen9975 dongwen9975 7年前

    I think you are looking for this:

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

    Output:

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

    点赞 评论 复制链接分享
  • dongye1942 dongye1942 8年前

    Something like this should work just how you want:

    <?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"}]"
    ?>
    
    点赞 评论 复制链接分享
  • dongqigu0429 dongqigu0429 8年前
        $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);
    
    点赞 评论 复制链接分享
  • duangan6797 duangan6797 8年前

    this here should work:

    $json = json_encode( array_combine( $array1, $array2 ) );
    
    点赞 评论 复制链接分享

相关推荐