0

i have an array full of objects , in each object there is properties i wanna collect a specific property in all the object that i have and assign them to a variable.

this is the array

[
  {
    "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"
  }
]

i wanna get the value of friend_id

whats the best practices to do so? thanks.

6
  • array_column() Commented May 23, 2018 at 21:29
  • array_column($your_array, 'friend_id') Commented May 23, 2018 at 21:30
  • array_column works just with the nested arrays right ! not with nested objects Commented May 23, 2018 at 21:33
  • In PHP 7.0 they added objects. Commented May 23, 2018 at 21:38
  • If you're getting the array from JSON, you can use the optional argument to json_decode() to create associative arrays instead of objects. Commented May 23, 2018 at 21:39

2 Answers 2

1

That looks like a json string, so you would need to decode it first:

$friends = json_decode($json_string, true);

The you can extract the ids with array column as suggested in comments, or a foreach loop if you are using php 5.4 or below:

$friend_ids = array_column($friends, 'friend_id');
//OR
$friend_ids=array();
foreach($friends as $friend)
    $friend_ids[] = $friend['friend_id'];
Sign up to request clarification or add additional context in comments.

Comments

0

You can use array map. What this will do is assign all the friend id's into a new array. I'm passing an anonymous function that returns just the friend id out of the object. For more info on 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);

1 Comment

this works just fine too , i guess using array_column method will be better and less hassle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.