【问题标题】:PHP get object with specific key value [duplicate]PHP获取具有特定键值的对象[重复]
【发布时间】:2017-08-22 18:53:38
【问题描述】:

我试图只获取这些带有 namespace="global" 的元字段对象,我该如何在 PHP 中做到这一点?

<?php $response = {"metafields":[{"id":30007223558,"namespace":"global"}, {"id":454872458451,"namespace":"local"}, {"id":154644565,"namespace":"global"}]} ?>
<?php $response = json_decode($response); ?>

【问题讨论】:

  • 这只会打印所有元字段数组,而不是按给定的命名空间过滤它们。

标签: php


【解决方案1】:
$response = json_decode($response, true);

$filtered['metafields'] = array_filter($response['metafields'], function ($item) {
   return $item['namespace'] === 'global'; 
});

var_dump($filtered);

array(1) {
  ["metafields"]=>
  array(2) {
    [0]=>
    array(2) {
      ["id"]=>
      int(30007223558)
      ["namespace"]=>
      string(6) "global"
    }
    [2]=>
    array(2) {
      ["id"]=>
      int(154644565)
      ["namespace"]=>
      string(6) "global"
    }
  }
}

【讨论】:

  • 谢谢你的作品 :) !
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-08
相关资源
最近更新 更多