使用php

时间:2019-07-16 09:37:15

标签: php json

我正在使用API​​,并且试图对返回给我的json对象进行排序。这是json对象的一小部分

Here is a small cut out of the json object

现在,我想对此进行排序,因为我只想保存部分数据。说我想在这里保存“ _ID”。我真正需要的数据还很遥远,但是我认为如果我能弄清楚如何得到这个数据,我就能弄清楚其余的数据。既然从图片中可以看到,它包含对象内部的许多对象以及数组中的数组,这让我很困惑,无法确定我想要的特定值

我尝试过这样的事情:

    $body = $response->getBody();

    $data = json_decode($body, true);

    $sortedData = $data."hits".hits[0]."_id";


    return $sortedData

也尝试不带引号,但我无法真正使它工作。我对PHP非常陌生。

2 个答案:

答案 0 :(得分:1)

从php 5.5开始,您可以使用array_column从数组中获取特定列:

$body = $response->getBody();
$data = json_decode($body, true);
$sortedData = array_column($data, '_id');
return $sortedData;

修改

根据我在数组样本中看到的内容,您想进行递归多维数组搜索(而不仅仅是二维)。

假设您有这样的数组:

$arr = array(
  array(
      'x' => '10',
      'name' => 'blah',
      'other' => array(
        '_id' => '26',
        'color' => '10x',
        )
  ),
  array(
      'x' => '7',
      'name' => 'blahblah',
      'other' => array(
        '_id' => '29',
        'color' => '7x',
        )
  ),
  array(
      'x' => '15',
      'name' => 'blahblahblah',
      'other' => array(
        '_id' => '27',
        'color' => '15x',
        )
  ),
  array(
      'x' => '1',
      'name' => 'sdf',
      'other' => array(
        '_id' => '41',
        'color' => '1x',
        )
  ),
  array(
      'x' => '4',
      'name' => '3dgdg',
      'other' => array(
        '_id' => '31',
        'color' => '4x',
        )
  ),
  array(
      'x' => '5',
      'name' => 'nmnmnm',
      'other' => array(
        '_id' => '36',
        'color' => '5x',
        )
  ),
  array(
      'x' => '21',
      'name' => 'dhshshhh',
      'other' => array(
        '_id' => '34',
        'color' => '21x',
        )
  )
);

您想获得_id键。在这种情况下,您可以尝试使用此功能:

function array_column_recursive(array $haystack, $needle) {
    $found = [];
    array_walk_recursive($haystack, function($value, $key) use (&$found, $needle) {
        if ($key == $needle)
            $found[] = $value;
    });
    return $found;
}

用法:

$ids = array_column_recursive($arr,'_id');
sort($ids);

print_r($ids);

参考:

  1. array_column
  2. array_column_recursive

答案 1 :(得分:1)

您已将这些对象解码为关联数组,因此$data['hits']['hits'][0]['_id']应该是访问该元素的正确方法。

https://www.php.net/manual/en/language.types.array.php解释了如何使用数组以及访问数组中的元素的基本知识。