-1

I am using PHP Codeigniter. I have a result from model as

Array ( [0] => stdClass Object ( [player_id] => 5bbbdfb4-6986-4383-90af-e3a12782b572 ) [1] => stdClass Object ( [player_id] => 46834ecd-ceef-49b8-a10a-706ee97ff729 ) )

I want to convert into

array("5bbbdfb4-6986-4383-90af-e3a12782b572","46834ecd-ceef-49b8-a10a-706ee97ff729")

I am breaking my head for 2 day on this. Any help appreciated.

5
  • Not sure of a CI specific way, but PHP 7+ you should be able to do array_column($array, "player_id") Commented Oct 21, 2019 at 7:21
  • Use typecastinglike this $new_array = (array)$my_objects; Commented Oct 21, 2019 at 7:23
  • I have used array_column($array, "player_id"), Where the output is Array ( [0] => 5bbbdfb4-6986-4383-90af-e3a12782b572 [1] => 46834ecd-ceef-49b8-a10a-706ee97ff729 ) Commented Oct 21, 2019 at 7:23
  • i suspect you get your results from a database ? if you use $query->result() you can als use $query->result_array() Commented Oct 21, 2019 at 7:27
  • Try using json_encode() method to convert it into json format. Also edit your question and add the code you are writing and getting this result. Commented Oct 21, 2019 at 7:41

2 Answers 2

0

You can use array_column in PHP 7+ as said by Nigen Sen.

You can also use following function too

$players = array_map(function($e) {
    return $e->player_id;
}, $records); // $records is your array object that need to be processed.

print_r( $players );
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks Vantiya, as yours and Nigen Sen's suggestion both returns Array ( [0] => 5bbbdfb4-6986-4383-90af-e3a12782b572 [1] => 46834ecd-ceef-49b8-a10a-706ee97ff729 ) how to convert again to array("5bbbdfb4-6986-4383-90af-e3a12782b572", "46834ecd-ceef-49b8-a10a-706ee97ff729")
@StephenPaulraj, do you know that Array([0] => 'www') is equal to Array('www')?
It's an array. each elements in array if you declare like array("5bbbdfb4-6986-4383-90af-e3a12782b572", "46834ecd-ceef-49b8-a10a-706ee97ff729") has it's default index starting from zero. It's a characteristics of an array.
An array is simply a variable that stores data of similar type with index/key.
@asken-p I do know that, I am passing the same to result to Onesignal i get the error. The acceptable key was array("x","y","z"), 'Array('www')' this is not going by.
0

You can try use this:

$arr = json_decode(json_encode($arr_obj), True);

also as

$arr = (array)$arr_obj;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.