如何动态输出对象数组的key:value并填充textarea?
动态遍历自定义字段数组生成格式化文本
核心逻辑
你的custom_fields数组中每个元素都是仅含单个键值对的对象(或关联数组),只需循环遍历数组,逐个提取每个元素的键和值,再拼接成目标格式即可。
代码实现(对象数组场景)
假设json_decode返回的是对象数组,代码如下:
$custom_fields = json_decode($object->custom_fields); $textareaContent = ''; foreach ($custom_fields as $field) { // 将对象转为关联数组,提取唯一键名 $key = array_keys(get_object_vars($field))[0]; // 获取对应的值 $value = $field->$key; // 键名格式化:下划线转空格+首字母大写(可按需调整) $formattedKey = ucfirst(str_replace('_', ' ', $key)); // 拼接每行内容 $textareaContent .= $formattedKey . ': ' . $value . "\n"; } // 移除末尾多余换行(可选) $textareaContent = rtrim($textareaContent);
代码实现(关联数组场景)
如果调用json_decode时传入第二个参数true,得到关联数组,代码可简化:
$custom_fields = json_decode($object->custom_fields, true); $textareaContent = ''; foreach ($custom_fields as $field) { $key = array_keys($field)[0]; $value = $field[$key]; $formattedKey = ucfirst(str_replace('_', ' ', $key)); $textareaContent .= $formattedKey . ': ' . $value . "\n"; } $textareaContent = rtrim($textareaContent);
效果说明
不管custom_fields数组新增或删除元素,循环都会自动遍历所有项,生成对应格式的文本,完全替代硬编码方式。你可根据需求修改$formattedKey的处理逻辑,适配不同的键名格式化要求。
内容的提问来源于stack exchange,提问作者Damon
相关产品推荐
相关产品推荐

