案例1:
需求:将json数据转换为数组,保存至元数据表postmeta。以下假设是前端提交的产品属性:颜色对应走廊图数据id。
{
"Red": ["123", "456", "invalid"],
"Blue": 789,
"Green": []
}
// 先运用wp_unslash(和php原生stripslashes类似)去除字符串里的反斜杠,接着再进行 JSON 解析。
$raw_data = json_decode(wp_unslash($_POST['_product_color_gallery']), true);
// 数据清理
$clean_data = [];
if (is_array($raw_data)) {
// 原始数据结构为[颜色名称 => [图片ID列表]],例如['red' => [1, 2, 3]]
foreach ($raw_data as $color => $ids) {
$clean_ids = array_map('absint', array_filter((array)$ids, 'is_numeric'));
if (!empty($clean_ids)) {
$clean_data[sanitize_title($color)] = $clean_ids;
}
}
}
1:先运用wp_unslash去除字符串里的反斜杠。如:{\”white\”:[1392,1391]}
2:json_decode将json数据解析为数组。第二个参数为true时,解析为数组。为false时,解析为对象。
$json_data = '{"name":"John","age":30,"city":"New York"}';
// 解析为对象(默认行为)
$obj_result = json_decode($json_data);
echo $obj_result->name; // 输出: John
// 解析为关联数组(第二个参数为true)
$arr_result = json_decode($json_data, true);
echo $arr_result['name']; // 输出: John
3:is_array($raw_data)判断解析后数据是否为数组,防止因非数组数据导致后续处理出错。
4:(array)$ids:确保$ids是数组类型,避免单个 ID 值引发错误。
5:array_filter(…, ‘is_numeric’):筛选出数组中所有数值类型的 ID,排除无效数据。
6:array_map(‘absint’, …):把筛选后的 ID 转换为非负整数,保证 ID 的有效性。
7:sanitize_title($color):对颜色名称进行处理,将其转换为小写字母、连字符连接的形式(比如把 “Deep Blue” 转换为 “deep-blue”),使其符合 URL 和数据库存储的规范。
经过清理后,$clean_data会变成:
[
'red' => [123, 456],
'blue' => [789]
]