PHP回显数组并置

时间:2019-04-19 08:55:23

标签: php

你能帮我吗?我的代码有点问题。

$json = '{"data":{"id":1,"first_name":"George","last_name":"Bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"}}';
$response = json_decode($json, true);

$output = ['data']['first_name'];
echo $response.$output;

错误:行号=> echo $response.$output;

上的数组到字符串的转换

我该如何解决?我做了很多尝试,但没有成功。

谢谢。

5 个答案:

答案 0 :(得分:1)

您可以使用'first_name'或'last_name'代替['data'] ['first_name']:

$(document).ready(function() {
  const randomImage = chooseBackground();
  if ($(window).width() < 650) //mobile browser
  {
    $('html, body').css('background-image', `url(${randomImage})`);
    $('html, body').css('background-repeat', 'no-repeat');
    $('html, body').css('background-attachment', 'fixed');
    $('html, body').css('background-size', 'cover');
    $('html, body').css('background-position', 'center');
  }
});

答案 1 :(得分:0)

您必须用于串联

$json = '{"data":{"id":1,"first_name":"George","last_name":"Bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"}}';
    $response = json_decode($json, true);


    $output = $response['data']['first_name'] ." " . $response['data']['last_name'];
    echo $output;
    die;

答案 2 :(得分:0)

$ response是一个数组,echo不知道如何显示数组。

改为使用它:

foreach($response['data'] as $value) {
   echo $value.PHP_EOF;
}

答案 3 :(得分:0)

如果阵列键是动态的,则:

$key = 'first_name';
echo $response['data'][$key];

即使'data'键可以更改,

$firstKey = 'data';
$secondKey = 'first_name';
echo $response[$firstKey][$secondKey];

答案 4 :(得分:0)

这将为您工作:

$json = '{"data":{"id":1,"first_name":"George","last_name":"Bluth","avatar":"https://s3.amazonaws.com/uifaces/faces/twitter/calebogden/128.jpg"}}';
$response = json_decode($json, true);

$output1 = "data";
$output2 = "first_name";
echo $response[$output1][$output2];