以特定格式向数组添加元素

时间:2017-03-15 18:47:27

标签: php arrays json

我有一个名为$ paises的数组:

Array
(
    [0] => Array
        (
            [life_sciences] => Array
                (
                    [0] => Array
                        (
                            [value] => Life Sciences
                        )

                    [1] => Array
                        (
                            [value] => 226
                        )

                    [2] => Array
                        (
                            [value] => 433
                        )

                    [3] => Array
                        (
                            [value] => 816
                        )


                )
            [telecom] => Array
                (
                    [0] => Array
                        (
                            [value] => Telecom
                        )

                    [1] => Array
                        (
                            [value] => 10
                        )

                    [2] => Array
                        (
                            [value] => 20
                        )

                    [3] => Array
                        (
                            [value] => 30
                        )


                )
        )
)

我需要使用json格式转换另一个数组:

{
    "dataset": [
        {
          "seriesname": "Life Sciences",
          "data": [{"value": "226"}, {"value": "433"}, {"value": "816"}]
        },
        {
          "seriesname": "Telecom",
          "data": [{"value": "10"}, {"value": "20"}, {"value": "30"}]
        },
        .
        .
        .
    ]
}

我正在做的是返回错误的数组格式:

$chart = array();

for ($i=0; $i < count($paises); $i++) {

        // here i get the value from index 0
        $chart["dataset"][]['seriesname'] = $paises[$i]['life_sciences'][0]['value'];

        // Here i remove the index 0 and reaorder the array indexes
        unset($paises[$i]['life_sciences'][0]);
        array_splice($paises[$i]['life_sciences'], 1, 1);

        // Here i get all values
        $chart["dataset"][]['data'] = $paises[$i]['life_sciences'];

}

结果:

{
    "dataset": [
        {
            "seriesname":"Life Sciences"
        },
        {
            "data":[{"value":"226"},{"value":"816"},{"value":"1098"}]
        },
        {
            "seriesname":"Telecom"
        },
        {
            "data":[{"value":"10"},{"value":"20"},{"value":"30"}]
        },
        .
        .
        .
    ]
}

请注意&#34;系列名称&#34;是&#34;数据&#34;:

{ "seriesname":"Life Sciences" }, { "data":[{"value":"226"},...] }

但我需要的是:

{ "seriesname":"Life Sciences" , "data":[{"value":"226"},...] }

我怎样才能以正确的方式做到这一点?

##########编辑1

我用过:

$chart = array();

for ($i=0; $i < count($paises); $i++) {

        $chart["dataset"][$i]['seriesname'] = $paises[$i]['life_sciences'][0]['value'];
        $chart["dataset"][$i]['data'] = $paises[$i]['life_sciences'];

        $chart["dataset"][$i]['seriesname'] = $paises[$i]['telecom'][0]['value'];
        $chart["dataset"][$i]['data'] = $paises[$i]['telecom'];

}

但只返回电信&#34;元素,忽视&#34; life_sciences&#34;

4 个答案:

答案 0 :(得分:1)

[]运算符每次使用时都会创建一个新的数组元素。所以当你这样做时:

$chart["dataset"][]['seriesname'] = $paises[$i]['life_sciences'][0]['value'];

您正在追加一个新元素,当您这样做时:

$chart["dataset"][]['data'] = $paises[$i]['life_sciences'];

您正在追加另一个新元素。你可以在同一个地方添加它们:

$char["dataset"][] = [
    "seriesname" => ...
    "data" => ...
];

或明确指定新索引:

$chart["dataset"][$i]['seriesname'] = ...
$chart["dataset"][$i]['data'] = ...

答案 1 :(得分:0)

尝试重新格式化阵列。

<?php

$json = '{
    "dataset": [
        {
          "seriesname": "Life Sciences",
          "data": [{"value": "226"}, {"value": "433"}, {"value": "816"}]
        }
    ]
}';

$data = json_decode($json)->dataset;

foreach ($data as $series) {
    $tempArr = Array();
    foreach ($series->data as $value) {
        array_push($tempArr, $value);
    }
    $series->data = $tempArr;
}

print_r($data);


?>

访问您的数据:

$data->data

或精子名称:

$data->seriesname

答案 2 :(得分:0)

$chart["dataset"][] = array(
    "seriesname" => $paises[$i]['life_sciences'][0]['value'],
    "data" => array_slice($paises[$i]['life_sciences'], 1)
);

我认为这适用于循环体

编辑1

在你的版本之后,我考虑应用类似的东西

$k = array_keys($paises[0]); // get array of keys names
for ($i=0; $i < count($k); $i++) { // iterate key names
    $chart["dataset"][] = array(
        "seriesname" => $paises[0][$k[$i]][0]['value'],
        "data" => array_slice($paises[0][$k[$i]], 1) // array without first element
    );
}

使用代码段来构建您的解决方案。

如果需要,再添加一个外部循环来迭代$paises

答案 3 :(得分:0)

您可以使用array_shift()获取数组的第一个元素(并将其从数组中删除):

function transformPaisesArray(array $paises): array
{
    $transformedPaisesArray = [];

    foreach ($paises[0] as $series) {

        // Take the first element from the array.
        $name = array_shift($series)['value'];
        // Add this first element and the rest as a new record to the target array.
        $transformedPaisesArray[] = [
            'seriesname' => $name,
            'data' => $series
        ];
    }

    // Wrap everything into the dataset field.
    return ['dataset' => $transformedPaisesArray];
}