You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何按JSON存储的条目序号打印对应预定义字符串?

问题排查
  • 多余的嵌套遍历逻辑错误:$item_list['item_sl']是单个字符串值(如"1"/"2"),不是数组,对其执行foreach遍历不仅无法拿到正确的序列号,还会触发PHP类型警告,导致动态变量根本没有被正确赋值,这是$all_print为空的核心原因。
  • 取值逻辑错误:你当前的赋值语句${'item'.$n} = $item_list['item_print'][$key];中,$item_list['item_print']同样是单个字符串,加[$key]是取字符串对应下标的单个字符,完全不符合你的需求;而且你只是把item_print的字符串值(如"flowers")赋给了动态变量,没有映射到你预先定义的$flowers/$cars变量的实际内容。
修复后的可用代码
$cars = 'Tesla is my favorite.';
$flowers = 'I love all flowers.';

$items_array = json_decode($items_data, true);
// 先按序列号升序排序,保证输出顺序符合要求
usort($items_array['item_list'], function($a, $b) {
    return intval($a['item_sl']) - intval($b['item_sl']);
});

$all_print = '';
foreach ($items_array['item_list'] as $item) {
    // 用可变变量映射到预定义变量的内容拼接
    $all_print .= ($$item['item_print'] ?? '') . ' ';
}
// 去掉末尾多余空格
$all_print = trim($all_print);
echo $all_print;
更优的实现方案

不推荐用零散的预定义变量和动态变量,容易产生变量污染,建议把预定义内容放到关联数组里管理,逻辑更清晰也更安全:

// 预定义内容统一存关联数组,后续新增内容只需维护这个数组即可
$print_map = [
    'cars' => 'Tesla is my favorite.',
    'flowers' => 'I love all flowers.'
];

$items_array = json_decode($items_data, true);
// 按序列号排序
usort($items_array['item_list'], fn($a, $b) => intval($a['item_sl']) - intval($b['item_sl']));

$all_print = '';
foreach ($items_array['item_list'] as $item) {
    $all_print .= ($print_map[$item['item_print']] ?? '') . ' ';
}
echo trim($all_print);

内容的提问来源于stack exchange,提问作者Ashonko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 06:57:03