Php get array attributes

Get only specific attributes with from Laravel Collection

I’ve been reviewing the documentation and API for Laravel Collections, but don’t seem to find what I am looking for: I would like to retrieve an array with model data from a collection, but only get specified attributes. I.e. something like Users::toArray(‘id’,’name’,’email’) , where the collection in fact holds all attributes for the users, because they are used elsewhere, but in this specific place I need an array with userdata, and only the specified attributes. There does not seem to be a helper for this in Laravel? — How can I do this the easiest way?

Other viewers might be interested in Collection::implode() . It can take a property and extract it from all the objects in the collection. This doesn’t answer this question exactly, but it might be useful for others who have come here from Google, as I did. laravel.com/docs/5.7/collections#method-implode

If you’re looking to do the inverse and get all properties except certain properties, use except Users::get()->except([‘password’, ‘secret_answer’]);

12 Answers 12

You can do this using a combination of existing Collection methods. It may be a little hard to follow at first, but it should be easy enough to break down.

// get your main collection with all the attributes. $users = Users::get(); // build your second collection with a subset of attributes. this new // collection will be a collection of plain arrays, not Users models. $subset = $users->map(function ($user) < return collect($user->toArray()) ->only(['id', 'name', 'email']) ->all(); >); 

Explanation

Читайте также:  How to convert json to xml java

First, the map() method basically just iterates through the Collection , and passes each item in the Collection to the passed in callback. The value returned from each call of the callback builds the new Collection generated by the map() method.

collect($user->toArray()) is just building a new, temporary Collection out of the Users attributes.

->only([‘id’, ‘name’, ’email’]) reduces the temporary Collection down to only those attributes specified.

->all() turns the temporary Collection back into a plain array.

Put it all together and you get «For each user in the users collection, return an array of just the id, name, and email attributes.»

Laravel 5.5 update

Laravel 5.5 added an only method on the Model, which basically does the same thing as the collect($user->toArray())->only([. ])->all() , so this can be slightly simplified in 5.5+ to:

// get your main collection with all the attributes. $users = Users::get(); // build your second collection with a subset of attributes. this new // collection will be a collection of plain arrays, not Users models. $subset = $users->map(function ($user) < return $user->only(['id', 'name', 'email']); >); 

If you combine this with the «higher order messaging» for collections introduced in Laravel 5.4, it can be simplified even further:

// get your main collection with all the attributes. $users = Users::get(); // build your second collection with a subset of attributes. this new // collection will be a collection of plain arrays, not Users models. $subset = $users->map->only(['id', 'name', 'email']); 

Источник

PHP — Extracting a property from an array of objects

and I want to extract an array of cats’ IDs in 1 line (not a function nor a loop). I was thinking about using array_walk with create_function but I don’t know how to do it. Any idea?

I don’t want to use a loop because I want to be able to assign the result in 1 line: $cats_id = myfunction($cats); /* should return Array(15, 18, 23) */

10 Answers 10

If you have PHP 5.5 or later, the best way is to use the built in function array_column() :

$idCats = array_column($cats, 'id'); 

But the son has to be an array or converted to an array

This solutions doesn’t answer the question because, array_column doesn’t work with an array of object s at all. Since PHP 7.0.0 is is possible: stackoverflow.com/a/23335938/655224

Warning create_function() has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.

You can use the array_map() function.
This should do it:

$catIds = array_map(create_function('$o', 'return $o->id;'), $objects); 

As @Relequestual writes below, the function is now integrated directly in the array_map. The new version of the solution looks like this:

$catIds = array_map(function($o) < return $o->id;>, $objects); 

this is the correct solution and will lead to the fact that every upcoming maintainer will be «wtf»‘d 😀

Here we go: $project_names = array_map(function($project) < return $project->name ;>, $projects ); However, it is noted in this blog post that it could be 2.5 times slower / memory intensive this way.

I found out, that everytime when the function is created with create_function the memory is growing up. If you write a programm with infinite loops and call the array_map with create_function in it you will always get an Out of memory. error sometime. So don’t use create_function and use array_map(function($o) < return $o->id; >, $objects);

The solution depends on the PHP version you are using. At least there are 2 solutions:

First (Newer PHP versions)

As @JosepAlsina said before the best and also shortest solution is to use array_column as following:

$catIds = array_column($objects, 'id'); 

Notice: For iterating an array containing \stdClass es as used in the question it is only possible with PHP versions >= 7.0 . But when using an array containing array s you can do the same since PHP >= 5.5 .

Second (Older PHP versions)

@Greg said in older PHP versions it is possible to do following:

$catIds = array_map(create_function('$o', 'return $o->id;'), $objects); 

But beware: In newer PHP versions >= 5.3.0 it is better to use Closure s, like followed:

$catIds = array_map(function($o) < return $o->id; >, $objects); 

The difference

First solution creates a new function and puts it into your RAM. The garbage collector does not delete the already created and already called function instance out of memory for some reason. And that regardless of the fact, that the created function instance can never be called again, because we have no pointer for it. And the next time when this code is called, the same function will be created again. This behavior slowly fills your memory.

Both examples with memory output to compare them:

BAD

while (true) < $objects = array_map(create_function('$o', 'return $o->id;'), $objects); echo memory_get_usage() . "\n"; sleep(1); > // the output 4235616 4236600 4237560 4238520 . 

GOOD

while (true) < $objects = array_map(function($o) < return $o->id; >, $objects); echo memory_get_usage() . "\n"; sleep(1); > // the output 4235136 4235168 4235168 4235168 . 

Источник

PHP: How do I get an attribute from a JSON array?

Using PHP, how do I get the geometery->location->lat & lng values from my JSON array above? For example (pseudo code):

3 Answers 3

You use json_decode and then $var->results[0]->geometry->location->lat; .

json_decode yields the following structure:

object(stdClass)[1] public 'status' => string 'OK' (length=2) public 'results' => array 0 => object(stdClass)[2] public 'types' => array 0 => string 'street_address' (length=14) public 'formatted_address' => string '5721 N Northcott Ave, Chicago, IL 60631, USA' (length=44) public 'address_components' => array 0 => object(stdClass)[3] public 'long_name' => string '5721' (length=4) public 'short_name' => string '5721' (length=4) public 'types' => array 0 => string 'street_number' (length=13) 1 => object(stdClass)[4] public 'long_name' => string 'Illinois' (length=8) public 'short_name' => string 'IL' (length=2) public 'types' => array 0 => string 'administrative_area_level_1' (length=27) 1 => string 'political' (length=9) 2 => object(stdClass)[5] public 'long_name' => string '60631' (length=5) public 'short_name' => string '60631' (length=5) public 'types' => array 0 => string 'postal_code' (length=11) public 'geometry' => object(stdClass)[6] public 'location' => object(stdClass)[7] public 'lat' => float 41.985886 public 'lng' => float -87.790746 public 'location_type' => string 'ROOFTOP' (length=7) public 'viewport' => object(stdClass)[8] public 'southwest' => object(stdClass)[9] public 'lat' => float 41.9827384 public 'lng' => float -87.7938936 public 'northeast' => object(stdClass)[10] public 'lat' => float 41.9890336 public 'lng' => float -87.7875984

Источник

Get array attribute in php if the value is yes

Actually, it is due to type casting. I would honestly suggest you change the yes to true or change the if to check if the value is yes .

7 Answers 7

You can access the fields of an array using square brackets and the key you want to access.

$arr = array( 'spec1' => 'yes' ,'spec2' => 'yes', 'spec3' => 'yes', 'spec4' => 'yes' ); if($arr['spec1'] == 'yes') < //do something >if($arr['spec2'] == 'yes') < //do something >

It’s simple: access the array key using the squared brackets:

foreach($myArray as $key => $value) < if($value == true) //do something >

array_walk (http://php.net/array_walk) will loop through each entry in your array

$array = [ 'spec1' => 'yes', 'spec2' => 'yes', 'spec3' => 'yes', 'spec4' => 'yes', ]; array_walk($array, function($value, $key) < if (strcasecmp($value, 'yes') === 0) < // case-insensitive comparison // do something. // Note: $key is available to the function if you need it >>); 
$array = array( 'spec1' => 'yes', 'spec2' => 'yes', 'spec3' => 'yes', 'spec4' => 'yes' ); foreach($array as $row) < if($row=='yes') //do somthing. >

You should try below code.

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Linked

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью