PHP编辑JSON数组

时间:2016-07-02 14:37:58

标签: php arrays json

我想在检查php中的元素后编辑我的JSON数组。我的意思是首先我需要检查JSON中的元素,如果它不存在我想要创建新的元素。如果它已经创建,我想将其添加为新元素。例如;

    { 
    "fruits": [
            {
        "Vitamin": "Vitamin C",
        "Name": "Apple",
        }
        {
        "Vitamin": "Vitamin B",
        "Name": "Banana",
        }
        {
        "Vitamin": "Vitamin D",
        "Name": "Watermelon",
        }
        {
        "Vitamin": "Vitamin C",
        "Name": "Orange",
        }
        {
        "Vitamin": "Vitamin C",
        "Name": "Mandarin",
        }
     ]
 }

让我们说这些是我的输入。我想检查每一个维生素对象,如果它已经创建了,我想让它像这样;

    { 
    "fruits": [
            {
        "Vitamin": "Vitamin C",
        "Name": ["Apple", "Orange", "Mandarin"]
        }
        {
        "Vitamin": "Vitamin B",
        "Name": "Banana",
        }
        {
        "Vitamin": "Vitamin D",
        "Name": "Watermelon",
        }
     ]
 }

我应该使用array_key_exists吗?我不知道该怎么办呢。我应该在每次输入输入时创建JSON吗?

1 个答案:

答案 0 :(得分:0)

据我了解,你正试图将关键词“维生素”分组。

为此,我会这样做:

/**
 * Group an array based on a "key column" and a "value column".
 * @param array $json       The array to transform.
 * @param string $keyCol    The column name from wich we will group
 * @param string $valCol    The value that we need to  group
 * @return array            The array grouped on the keycol.
 */
function groupJsonOnKey(array $json, $keyCol, $valCol) {
    $groupedArray = [];
    foreach ($json as $val) {
        $key = $val[$keyCol];
        if (!isset($groupedArray[$key]))
            $groupedArray = (object) [$keyCol => $key, $valCol => []];
        $groupedArray[$key]->$valCol[] = $val[$valCol];
    }
    return $groupedArray;
}

//We load the data and parse it to an array
$jsonData = json_decode("DECODE YOUR JSON TO AN ARRAY", true);

$groupedArray = groupJsonOnKey($jsonData['fruits'], 'Vitamin', 'Name');

//Now we recreate the expected output
$newData = new stdClass();
$newData->fruits = array_values($groupedArray);