json,php-从数组输出字符串

json,php-从数组输出字符串,php,json,Php,Json,我试图将JSON数据解码为PHP,然后将其输出到站点。如果我有以下资料: { "name": "josh", "type": "human" { { "name": "josh", "type": "human", "friends": [ { "name": "ben", "type": "robot" }, { "name": "tom", "type": "alien" } ],

我试图将JSON数据解码为PHP,然后将其输出到站点。如果我有以下资料:

{
  "name": "josh",
  "type": "human"
{
{
  "name": "josh",
  "type": "human",
  "friends": [
    {
      "name": "ben",
      "type": "robot"
    },
    {
      "name": "tom",
      "type": "alien"
    }
  ],
  "img": "img/path"
}
//specify the name of the friend like this:
$name = "ben";

$friends = $json["friends"];

//loop through the array of friends;
foreach($friends as $friend) {
    if ($friend["name"] == $name) echo $friend["type"];
}
我可以这样做(在PHP中),以显示或输出我的
类型

$file = "path";
$json = json_decode($file);

echo $json["type"]; //human
因此,如果我有以下几点:

{
  "name": "josh",
  "type": "human"
{
{
  "name": "josh",
  "type": "human",
  "friends": [
    {
      "name": "ben",
      "type": "robot"
    },
    {
      "name": "tom",
      "type": "alien"
    }
  ],
  "img": "img/path"
}
//specify the name of the friend like this:
$name = "ben";

$friends = $json["friends"];

//loop through the array of friends;
foreach($friends as $friend) {
    if ($friend["name"] == $name) echo $friend["type"];
}

如何输出my friend
ben
是什么?

使用类似foreach的循环并执行以下操作:

{
  "name": "josh",
  "type": "human"
{
{
  "name": "josh",
  "type": "human",
  "friends": [
    {
      "name": "ben",
      "type": "robot"
    },
    {
      "name": "tom",
      "type": "alien"
    }
  ],
  "img": "img/path"
}
//specify the name of the friend like this:
$name = "ben";

$friends = $json["friends"];

//loop through the array of friends;
foreach($friends as $friend) {
    if ($friend["name"] == $name) echo $friend["type"];
}

要获取数组格式的解码数据,您需要提供
true
作为
json\u decode
的第二个参数,否则它将使用默认值,即
object
表示法。当您需要查找特定用户时,可以轻松创建一个函数来缩短流程

$data='{
  "name": "josh",
  "type": "human",
  "friends": [
    {
      "name": "ben",
      "type": "robot"
    },
    {
      "name": "tom",
      "type": "alien"
    }
  ],
  "img": "img/path"
}';

$json=json_decode($data);
$friends=$json->friends;
foreach( $friends as $friend ){
    if( $friend->name=='ben' )echo $friend->type;
}

function finduser($obj,$name){
    foreach( $obj as $friend ){
        if( $friend->name==$name )return $friend->type;
    }
}

echo 'Tom is a '.finduser($friends,'tom');
试试这个

$friend_name = "ben";
$json=json_decode($data);
$friends=$json->friends;
foreach( $friends as $val){
    if($friend_name == $val->name)
    {
        echo "name = ".$val->name;
        echo "type = ".$val->type;
    }    
}

我们鼓励您使用最适合此类工作的
jq
。你可能想在类似的问题上检查我的答案。