简体   繁体   中英

How can I merge different values as an array on own key

I have arrays included same keys but, values can be different. I have arrays included same keys but, values can be different.

my arrays:

$arr1 = json_decode('{

"Chain": "Monaco Chain",

"Style": "Monaco Swarovski",

"Gauge": "9.50 mm",

"Length": "30.00",

"Color": "YELLOW",

"Karat": "21",

"Lock": "Long",

"2 Tone": "Yes",

"Alternate": "Yes"

}', true);

$arr2 = json_decode('{

"Chain": "Monaco Chain",

"Style": "Monaco Swarovski",

"Gauge": "9.50 mm",

"Length": "30.00",

"Color": "GREEN",

"Karat": "21",

"Lock": "Long",

"2 Tone": "Yes",

"Alternate": "Yes"

}', true);

$arr3 = json_decode('{

"Chain": "Monaco Chain",

"Style": "Monaco Swarovski",

"Gauge": "9.50 mm",

"Length": "30.00",

"Color": "YELLOW",

"Karat": "21",

"Lock": "Long",

"2 Tone": "No",

"Alternate": "Yes"

}', true);

$arr4 = json_decode('{

"Chain": "Monaco Chain",

"Style": "Monaco Swarovski",

"Gauge": "9.50 mm",

"Length": "300.00",

"Color": "YELLOW",

"Karat": "21",

"Lock": "Long",

"2 Tone": "Yes",

"Alternate": "Yes"

}', true)

I have to merge different values as an array and keep them in their own key, so I should get this output:

'{

"Chain": "Monaco Chain",

"Style": "Monaco Swarovski",

"Gauge": "9.50 mm",

"Length": ["30.00", "300.00"],

"Color": ["YELLOW", "GREEN"],

"Karat": "21",

"Lock": "Long",

"2 Tone": ["Yes", "No"],

"Alternate": "Yes"

}'

Note: Please don't care the jsons.

Thanks for your help and time.

function key_concat(...$arrays) {
    if (count($arrays) == 1) return $arrays[0];
    $temp = array_shift($arrays);
    for ($i = 0; $i < count($arrays); $i++) {
        foreach($arrays[$i] as $key => $value) {
            if ((is_string($temp[$key]) && trim($temp[$key]) != trim($arrays[$i][$key])) ||
                (is_array($temp[$key]) && array_search($arrays[$i][$key], $temp[$key]) === false)
            ) {
                if (is_string($temp[$key])) {
                    $temp[$key] = Array($temp[$key], $arrays[$i][$key]);
                } else if (is_array($temp[$key])) {
                    $temp[$key][] = $arrays[$i][$key];
                }
            }
        }
    }
    return $temp;
}
print_r(key_concat($arr1, $arr2, $arr3, $arr4, $arr5));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM