【问题标题】:How to get a specific value from a json array out of a list of arrays如何从数组列表中的json数组中获取特定值
【发布时间】:2021-03-25 06:29:26
【问题描述】:

大家,我只是想找到一种从 JSON 数组中获取链接值的方法,在 Id 的帮助下搜索了数组之后。我正在使用 PHP 的 file_get_contents 并且从中获取信息的网页看起来像

[{
    "id":"2972",
    "name": "AbC",
    "link":"any link",
    "epg": "any link",
    "dur": "disabled",
    "language": "y",
    "category": "TOP 100",
    "logo": "any url here"
},
{
    "id": "1858",
    "name": "Efg",
    "link": "url",
    "epg": "url",
    "dvr": "disabled",
    "language": "E",
    "category": "TOP 100",
    "logo": "url"
}]

从这里假设我得到了一个 ID 1858,所以我必须从具有 1858 的 ID 数组中找到一个链接

我是 PHP 的初学者,只是在处理一段代码并试图获得它的解决方案,非常感谢感谢您的回答和宝贵的时间。

【问题讨论】:

  • 发布的数据不是有效的 json。那只是一个接一个输出的两个对象。它们实际上是否在一个数组中:[ ... ][{...}, {...}] 之间有逗号?
  • 先生,我在网页上有一个类似的数组,但缺少一些逗号如果您愿意,我是否应该重新编辑并添加这些逗号以使其看起来像一个数组或 json
  • 请按原样发布数据"。如果我们不能信任我们看到的数据,我们很难提供帮助。可以删除不相关的数据(或如果有很多对象,请删除一些对象),但请确保您发布的内容仍然有效。您还应该发布您尝试过的代码、预期结果以及当前发生的情况。我们很高兴帮助您解决现有代码的问题,但我们不在这里为你写。
  • 如果可能的话,请使用用户代理 REDLINECLIENT G90 V10.36 访问access.richtv1.com/…,因为数据没有被准确复制。
  • 也感谢您的回复

标签: php arrays json file-get-contents


【解决方案1】:

您可以使用 array_column 来映射成对的 json 键/值:

<?php
$json ='
[
    {
        "id": 3,
        "link": "http:\/\/example.com\/3"
    },
    {
        "id": 5,
        "link": "http:\/\/example.com\/5"
    }
]';

$data = json_decode($json, true);

if($data !== null) {
    echo array_column($data, 'link', 'id')[5] ?? null;
}

输出:

http://example.com/5

为了理解这一点,我们可以查看array_column的结果。

var_export(array_column($data, 'link', 'id'));

输出:

array (
  3 => 'http://example.com/3',
  5 => 'http://example.com/5',
)

所以使用上面的代码,我们正在检查并输出 5 的关联索引(原始 id)。

【讨论】:

  • 非常感谢您的快速回复
【解决方案2】:

如果你使用file_get_contents('php://input');,那么你应该尝试这个来访问json数据

$json = file_get_contents('php://input'); //get json data in variable
$array = json_decode($json);  //parse json data in php array

// assecc the array with use of foreach loop
foreach($array as $obj){
//access the json element here like $id = $obj->id; $url = $obj->link;
//if you want to check the id value in array you can compare value with if condition
$id = $obj->id;
// find link for specific id
if($id =='1858'){
   $url = $obj->link;
   echo $url; // do something with link
   //you can use break; statement if you found your element and terminate the loop
}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-20
    • 2019-06-13
    • 2019-10-23
    • 2019-10-08
    • 2020-06-25
    • 1970-01-01
    相关资源
    最近更新 更多