从php生成关联数组json

时间:2016-10-15 08:49:09

标签: php arrays json

预期的JSON结构:

Name

当前JSON:

fruitflavor

代码:

{"music" : [ 
    { 
        "title" : "Jazz in Paris",
        "album" : "Jazz & Blues"
    },
    { 
        "title" : "Jazz in Paris",
        "album" : "Jazz & Blues"
    }
    .......
    .......
]}

4 个答案:

答案 0 :(得分:1)

只需在foreach之外创建一个数组,然后使用subarray[]追加到主数组中。

像这样,

$audio=array();
$audio["music"]=array();
foreach ($this->data as  $value)
        {
            $sub = array();
            $sub['title'] = $value['title'];
            $sub['album'] = "devotional";
            $audio["music"][]=$sub;
        }

echo json_encode($audio);

这将创建一个音乐数组,并将每个子数组作为其对象。

答案 1 :(得分:0)

您需要将内容包装在另一个数组中。只需更改$sub = array(); foreach ($this->data as $value) { $sub['title'] = $value['title']; $sub['album'] = "devotional"; } $audio = array('music'=>array($sub)); // just add array so whole things are wrap in another array. echo json_encode($audio);

delimiter $
CREATE Procedure P1()
BEGIN
     DECLARE EndCurs BOOLEAN DEFAULT 0;
     DECLARE V_Id CHAR(3);
     DECLARE V_name CHAR(30);
     DECLARE Curs CURSOR FOR SELECT id,name
                             FROM MyTable where age >50
                             FOR UPDATE;
     DECLARE CONTINUE 
                HANDLER FOR NOT FOUND 
                SET EndCurs :=1;
     START Transaction;         
     OPEN Curs;

     WHILE (not EndCurs) DO
          /* some stuff */
     END WHILE;
     CLOSE Curs;
    COMMIT;

END;
$
delimiter ;

答案 2 :(得分:0)

更改现有代码中的位 -

只需将额外数组添加到$sub array($sub)

$audio = array('music'=>array($sub));

答案 3 :(得分:0)

试试这个

    $sub = array();
    foreach ($this->data as  $value)
    {
        $temp['title'] = $value['title'];
        $temp['album'] = "devotional";
        array_push($sub, $temp);
    }
    $audio = array('music'=>$sub);
    echo json_encode($audio);