In my one project i required to extract each phone
from input json. Json input something like:
[
{
"name": "Niyo",
"email": "niyo@ymail.com",
"phone": "8989457845"
},
{
"name": "Picks",
"email": "picks.p@gmail.com",
"phone": "7878121245"
},
{
"name": "Chintz",
"email": "Chintz@gmail.com",
"phone": "8745421254"
},
{
"name": "Kabiru Wabyu",
"email": "kabiru.v@gmail.com",
"phone": ""
},
{
"name": "Rons",
"email": "",
"phone": "9898989898"
}
]
I know one solutions to extract each phone from input json contact
foreach($contacts as $phone){ $phones[]=$phone->phone; }
Is there any alternate way in php/laravel to get all values from input json for specific key ?
This should return what you're seeking, provided that you have php 5.5 or more recent. Not sure if it's necessary to set the second parameter of json_decode to TRUE, which returns an array of arrays, rather than array of objects.
$x = json_decode(yourjson, TRUE);
$phones = array_column($x, 'phone');
Since you already have this as an array, you can use array_map
$phones = array_map(function($contact) { return $contact->phone; }, $contacts);
You can use Laravel helper functions:
$phones = array_pluck($contacts, 'phone');
or a Collection:
$contacts = collect($contacts);
$phones = $contacts->pluck('phone');
and don't forget to parse the JSON as an array:
$contacts = json_decode($json, true);