如何将 stdClass 对象打印为字符串?



当我尝试使用 print_r 命令打印数组时出现以下错误 解析错误:syntax error, unexpected '$array' (T_VARIABLE) in /home4/rajatwalia/student.rwalia.com/wp-content/plugins/insert-php/includes/shortcodes.php(66) : eval()'d code on line 6

这是在wordpress中用php简码插件编写的代码

global $wpdb;
$profile_id = um_profile_id();
$result = $wpdb->get_results( "SELECT meta_value FROM wp_usermeta WHERE 
meta_key = 'student_id' AND user_id = $profile_id;" );
$array = json_decode(json_encode($result),true);
//$array[0] -> $studentid;  
print_r $array;
//print_r($result);

我正在使用 json,因为否则我的结果是一个 stdClass,我想要一个字符串

print_r是一个函数,应该像这样调用:

print_r($array);

可以使用函数序列化将类转换为字符串。

print_r(serialize($array));

或者,如果您只想获取数组的值,则可以使用函数 implode:

print_r(implode(', ', $array));

此函数将转换以逗号分隔的字符串中的数组值。内爆的第一个参数是分隔符,第二个参数是将按字符串转换的数组。

如果你想同时拥有数组的名称和值。您可以这样做:

//variable that will storage the string
$string = "";
/** this loop will run all the array, the $key variable will storage the name of 
*the array position(the key), the $value variable will storage the value of the 
*array in that position
*/
foreach ($array as $key => $value) {
$string .= $key . ": " . $value . ", ";
}
print_r($string);

最新更新