首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP用foreach创建JSON

问PHP用foreach创建JSON
EN

Stack Overflow用户
提问于 2017-05-07 17:22:07
回答 2查看 7.4K关注 0票数 0

我有下面的PHP代码,可以从数组中用foreach创建JSON:

代码语言:javascript
复制
$array = array('one', 'two', 'three', 'four');

foreach ($array as $key => $value) {
    $temp = array(
                'text' => 'Hello', 
                'text1' => 5,
                'collect' => array(
                                $value => array(
                                            'xx' => 'yy',
                                            'key' => $key
                                        )
                            )
            );


    echo json_encode($temp);
}

产出如下:

代码语言:javascript
复制
{
    "text":"Hello",
    "text1":5,
    "collect":{"one":{"xx":"yy","key":0}}
}

{
    "text":"Hello",
    "text1":5,
    "collect":{"two":{"xx":"yy","key":1}}
}

{
    "text":"Hello",
    "text1":5,
    "collect":{"three":{"xx":"yy","key":2}}
}

{
    "text":"Hello",
    "text1":5,
    "collect":{"four":{"xx":"yy","key":3}}
}

但我想要这个:

代码语言:javascript
复制
{
    "text":"Hello",
    "text1":5,
    "collect": {
        "one":{"xx":"yy","key":0},
        "two":{"xx":"yy","key":1},
        "three":{"xx":"yy","key":2},
        "four":{"xx":"yy","key":3}
    }
}

我得到了单个的4个JSON对象,但是我只需要一个带有collect对象的对象。

我不明白..。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-05-07 17:26:20

试试这段简单的代码,其中我们在foreach之前有一个声明。

Try this code snippet here

代码语言:javascript
复制
<?php

ini_set('display_errors', 1);
$array = array('one', 'two', 'three', 'four');

$temp = array(
    'text' => 'Hello',
    'text1' => 5,
    'collect' => array()
);
$collect = array();
foreach ($array as $key => $value)
{
    $collect[$value] = array(
        'xx' => 'yy',
        'key' => $key
    );
}
$temp["collect"]=$collect;
echo json_encode($temp);

输出:

代码语言:javascript
复制
{
    "text": "Hello",
    "text1": 5,
    "collect": {
        "one": {
            "xx": "yy",
            "key": 0
        },
        "two": {
            "xx": "yy",
            "key": 1
        },
        "three": {
            "xx": "yy",
            "key": 2
        },
        "four": {
            "xx": "yy",
            "key": 3
        }
    }
}
票数 0
EN

Stack Overflow用户

发布于 2017-05-07 17:23:37

您需要循环遍历这些值数组并将其追加到临时数组的“collect”键中。

代码语言:javascript
复制
$array = array('one', 'two', 'three', 'four');
$temp = array(
    'text' => 'Hello', 
    'text1' => 5,
    'collect' => array()
);

foreach ($array as $key => $value) {
    $temp['collect'][$value] = array(
        'xx' => 'yy',
        'key' => $key
    );
}

echo json_encode($temp);

下面是演示:https://eval.in/788929

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43834471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档