30 lines
890 B
Plaintext
30 lines
890 B
Plaintext
<?php
|
|
namespace App\Services;
|
|
|
|
class UserFun
|
|
{
|
|
public static function Json2Arr($data, $prefix = '') {
|
|
// 如果傳進來的是字串,就 decode 一次
|
|
if (is_string($data)) {
|
|
$arr = json_decode($data, true);
|
|
if (!is_array($arr)) {
|
|
return []; // 無效 JSON,回傳空陣列或你可自訂錯誤處理
|
|
}
|
|
} elseif (is_array($data)) {
|
|
$arr = $data;
|
|
} else {
|
|
return []; // 不是 JSON 字串也不是陣列,回傳空
|
|
}
|
|
$result = [];
|
|
foreach ($arr as $key => $value) {
|
|
$fullKey = $prefix === '' ? $key : "{$prefix}_{$key}";
|
|
if (is_array($value)) {
|
|
$result += self::Json2Arr($value, $fullKey);
|
|
} else {
|
|
$result[$fullKey] = $value;
|
|
}
|
|
}
|
|
return $result;
|
|
}
|
|
}
|