首页 > 解决方案 > json_decode 之后的多个选定值的 print_r

问题描述

我正在尝试在 wordpress 的表单提交确认中显示来自 API 响应的选定数据。这将在现实中使用 POST,但已使用 GET 进行测试。我有以下内容可用于显示 JSON 响应中的单个值(在本例中为“id”)。我想知道如何编写 print_r 指令来打印 2 或 3 个值(按名称而不是位置)。例如显示 'id' 和 'login' 值。我使用 github api 进行演示。

add_filter( 'gform_confirmation_4', 'custom_confirmation', 10, 4 );
function custom_confirmation( $confirmation, $form, $entry, $ajax ) {
$response = wp_remote_get( 'https://api.github.com/users/someuser' );

if ( is_wp_error( $response ) ) {
echo 'An error happened';
} else {
$body = wp_remote_retrieve_body( $response );
$data = json_decode( $body );
}

$confirmation .= print_r( $data->id, true );
return $confirmation;

}

我假设像

$confirmation .= print nl2br(print_r($data->id, true), ($data->login, true));

但是找到如何使用这种'->' 格式打印多个特定值是我在手册或论坛中看不到的。

标签: phparraysjsonwordpress

解决方案


->无关紧要。您的问题是尝试使用单个 print_r 语句打印多个变量。这对于普通变量和对象属性都是一个问题。

您要么只使用连接在一起的多个 print_r 语句(例如$confirmation .= print_r( $data->id, true )." ".print_r($data->login, true);,或者您可以切换到使用 var_dump (例如,请参见此处)。


推荐阅读