循环遍历数组

时间:2014-04-24 08:31:06

标签: php arrays json for-loop foreach

这是我的原始代码

    [Width] => Array
        (
            [0] => 400px
            [1] => 323a
        )

    [Height] => Array
        (
            [0] => 244px
            [1] => 244px
        )

    [Captions] => Array
        (
            [0] => [{ "captionId": 1,"caption": "Learning Clock Face is fun - you learn importance of time.","xyCordinates": "40px-250px","dimension": "70%-20%"},{"captionId": 2,"caption": "12 AM or 12 PM","xyCordinates": "40px-250px","dimension": "70%-20%"}]
            [1] => [{ "captionId": 1,"caption": "Learning Clock Face is fun - you learn importance of time.","xyCordinates": "40px-250px","dimension": "70%-20%"},{"captionId": 2,"caption": "12 AM or 12 PM","xyCordinates": "40px-250px","dimension": "70%-20%"}]
        )
)

上面的代码是我的实际代码,现在我需要循环它,以便我的代码看起来类似于下面的代码。请帮帮我。

页面ID不断递增。请帮帮我

"Pages": [
    {
      "pageId": "1",
      "resource": {
        "width": "220px",
        "height": "120px",
        "captions": [
          {
            "captionId": 1,
            "caption": "Learning alphabets is fun - you learn what to eat.",
            "xyCordinates": "40px-250px",
            "dimension": "70%-20%"
          }
        ]
      },
      "pageOrder": 1,
      "state": 1
    }]

1 个答案:

答案 0 :(得分:0)

首先你必须将数据格式化为你想要在php中的结构,然后最后你必须编码为json .. 您也可能必须读取数组中的数据并创建模型类,然后编码为JSON

json_encode()

示例代码

$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);

echo json_encode($arr);

输出将是 {"":1," B":2" C":3," d&#34:4," E& #34;:5}