当使用 `json_decode()` 将 json 字符串转为 php 对象后,需明确目标数据位于对象的哪个属性下;本例中待遍历的是 `$topic_obj->text` 这一数组属性,而非整个对象本身。
在 PHP 中,json_decode($json, $assoc = false) 默认返回一个 stdClass 对象,其结构严格对应原始 JSON。这意味着:
✅ 正确做法是:定位到目标数组属性,再对其迭代:
$Topic_OBJ = json_decode($this->api_local_get($url));
$Text_IDS = "";
// ✅ 正确:遍历 $Topic_OBJ 对象的 Text 属性(它是一个数组)
foreach ($Topic_OBJ->Text as $text) {
$Text_IDS .= $text->Text_id . ',';
}
// 输出示例:'794887707,794887711,'⚠️ 注意事项:
if (isset($Topic_OBJ->Text) && is_array($Topic_OBJ->Text)) {
foreach ($Topic_OBJ->Text as $text) {
if (isset($text->Text_id)) {
$Text_IDS .= $text->Text_id . ',';
}
}
}$textIds = array_column((array)$Topic_OBJ->Text, 'Text_id');
$Text_IDS = implode(',', $textIds) . ',';总结:foreach 作用于对象本身 ≠ 遍历其内部数组属性;务必通过 ->属
性名 明确路径访问嵌套结构。这是 JSON 解析后对象遍历中最常见的误区之一。