获取数组对象中的所有属性值

时间:2018-05-23 21:28:30

标签: php laravel

我有一个充满对象的数组,在每个对象中都有属性我希望在我拥有的所有对象中收集特定属性并将它们分配给变量。

这是数组

[
  {
    "id": 23,
    "user_id": 2,
    "friend_id": 2,
    "created_at": "2018-05-23 21:00:07",
    "updated_at": "2018-05-23 21:00:07"
  },
  {
    "id": 31,
    "user_id": 2,
    "friend_id": 1,
    "created_at": "2018-05-23 21:00:07",
    "updated_at": "2018-05-23 21:00:07"
  },
  {
    "id": 32,
    "user_id": 2,
    "friend_id": 4,
    "created_at": "2018-05-23 21:00:07",
    "updated_at": "2018-05-23 21:00:07"
  }
]

我想获得 friend_id

的价值

最佳做法是什么? 感谢。

2 个答案:

答案 0 :(得分:1)

这看起来像一个json字符串,所以你需要先解码它:

$friends = json_decode($json_string, true);

您可以按照注释中的建议使用数组列提取ID,如果使用的是php 5.4或更低版本,则可以使用foreach循环提取:

$friend_ids = array_column($friends, 'friend_id');
//OR
$friend_ids=array();
foreach($friends as $friend)
    $friend_ids[] = $friend['friend_id'];

答案 1 :(得分:0)

您可以使用数组映射。这样做是将所有朋友ID分配到一个新数组中。我传递了一个匿名函数,该函数只返回对象中的朋友ID。有关array_map的更多信息:http://php.net/manual/en/function.array-map.php

<?php 
$json = '[
  {
    "id": 23,
    "user_id": 2,
    "friend_id": 2,
    "created_at": "2018-05-23 21:00:07",
    "updated_at": "2018-05-23 21:00:07"
  },
  {
    "id": 31,
    "user_id": 2,
    "friend_id": 1,
    "created_at": "2018-05-23 21:00:07",
    "updated_at": "2018-05-23 21:00:07"
  },
  {
    "id": 32,
    "user_id": 2,
    "friend_id": 4,
    "created_at": "2018-05-23 21:00:07",
    "updated_at": "2018-05-23 21:00:07"
  }
]';

$jsonObject = json_decode($json);

$newArray = array_map(function($a) {
  return $a->friend_id;
}, $jsonObject);

print_r($newArray);