Array of PHP Objects

Array of PHP Objects

The best place to find answers to general (and somewhat easy questions) such as this is to read up on PHP docs. Specifically in your case you can read more on objects. You can store stdObject and instantiated objects within an array. In fact, there is a process known as 'hydration' which populates the member variables of an object with values from a database row, then the object is stored in an array (possibly with other objects) and returned to the calling code for access.

-- Edit --

class Car
{
public $color;
public $type;
}

$myCar = new Car();
$myCar->color = 'red';
$myCar->type = 'sedan';

$yourCar = new Car();
$yourCar->color = 'blue';
$yourCar->type = 'suv';

$cars = array($myCar, $yourCar);

foreach ($cars as $car) {
echo 'This car is a ' . $car->color . ' ' . $car->type . "\n";
}

how to build arrays of objects in PHP without specifying an index number?

This code

 $pages_array[1]->slug = "a";

is invalid anyways - you'll get a "strict" warning if you don't initialize the object properly. So you have to construct an object somehow - either with a constructor:

 $pages_array[] = new MyObject('index', 'title'....)

or using a stdclass cast

 $pages_array[] = (object) array('slug' => 'xxx', 'title' => 'etc')

How do I work with an array object in PHP?

There is no need to json_encode the data. Since the data is an instance of Laravel Collection, you can manipulate it like so

$item = $data->firstWhere('label', '1mm+'); // get the item
$data = $data->filter(fn($value, $key) => $value->label !== '1mm+') // remove $item from $data
->push($item); // move $item to the end of data

Array of objects - set keys by object field value

You could use array_combine() and array_column().

array_column() to get the keys, and array_combine() to build the array using the extracted keys and objects as values.

$demo = [
(object) ['key' => 'a', 'xxx' => 'xxx'],
(object) ['key' => 'b', 'xxx' => 'xxx'],
(object) ['key' => 'c', 'xxx' => 'xxx']
];

print_r(array_combine(array_column($demo, 'key'), $demo));

Output:

Array
(
[a] => stdClass Object
(
[key] => a
[xxx] => xxx
)

[b] => stdClass Object
(
[key] => b
[xxx] => xxx
)

[c] => stdClass Object
(
[key] => c
[xxx] => xxx
)

)

See a working demo.

PHP create and access properties in an array of objects

<?php
$arrayOfObjects = array(
(object)array('color' => 'red', 'size' => 10),
(object)array('color' => 'blue', 'size' => 4),
(object)array('color' => 'green', 'size' => 6),
);

foreach($arrayOfObjects as $obj) {
echo $obj->color;
echo $obj->size;
}

PHP arrays can have string indexes as well. Would this work out for your needs?

<?php
$arrayOfObjects = array(
array('color' => 'red', 'size' => 10),
array('color' => 'blue', 'size' => 4),
array('color' => 'green', 'size' => 6),
);

foreach($arrayOfObjects as $obj) {
echo $obj['color'];
echo $obj['size'];
}

PHP, array of objects, how can I use one set of object values as the array keys

As of PHP 7, you can use array_column() on objects, with the third parameter as the column to index by...

$questions = array_column($data, "name", "id");

PHP: group array of objects by id, while suming up object values

i hope this answer help you
first i will change objects to array and return the result to array again

 $values =[
[
"id"=> "xx",
"points"=> 25
],
[
"id"=> "xx",
"points"=> 40
],
[
"id"=> "xy",
"points"=> 40
],
];
$res = array();
foreach($values as $vals){
if(array_key_exists($vals['id'],$res)){
$res[$vals['id']]['points'] += $vals['points'];
$res[$vals['id']]['id'] = $vals['id'];
}
else{
$res[$vals['id']] = $vals;
}
}
$result = array();
foreach ($res as $item){
$result[] = (object) $item;
}

output enter image description here

Stop PHP Object behaving like reference

You need to clone each of the objects inside $pool, otherwise a reference to the same set of objects is held in every copy of $pool that you create. It's not the array which is "behaving like a reference", it's the objects within it, which are behaving as they're supposed to.

Doing this will result the behaviour you want:

$vars = [];
foreach ($items as $i => $item) {

$vars[$i] = $item;
$vars[$i]->pool = $pool;

//clone each of the objects
foreach($vars[$i]->pool as $key => $obj) {
$vars[$i]->pool[$key] = clone $obj;
}

$vars[$i]->pool[$item->id]->processed = true;
}

See http://php.net/manual/en/language.oop5.cloning.php for more info on cloning.

PHP Object array to javascript associative array

Isn't the hardest task, as you almost have your desired format. At first I have to add, that you possibly even not have to filter out the address field, as the plugin may ignore it completly. If this is the case, you could simply do this

var characters = <?php json_encode(['data' => $chars]); ?>;

And if you really need to filter out the address field, you could use array_map.

$chars = array_map(function($item) {
// at this point, you don't need an object, as json_encode do the
// same for objects and associative arrays
return [
"id" =>$item->id,
"name" => $item->name
];
}, $chars);


Related Topics



Leave a reply



Submit