Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP calling tree objects

Tags:

arrays

php

$var is an array:

Array (
    [0] => stdClass Object ( [ID] => 113 [title] => text )
    [1] => stdClass Object ( [ID] => 114 [title] => text text text )
    [2] => stdClass Object ( [ID] => 115 [title] => text text )
    [3] => stdClass Object ( [ID] => 116 [title] => text )
)

How can we call [title] from some [ID]? (without touching [0], [1], [2], [3])

Like, if we call $var['114']['title] it should give text text text

like image 917
James Avatar asked Apr 10 '26 06:04

James


2 Answers

You can't.

You can make a new array which has the ID as keys, and after that you can access the title fast, or you can loop through the array every time you need to search some ID.

like image 158
Sjoerd Avatar answered Apr 11 '26 18:04

Sjoerd


Why don't you structure it like:

Array (
    [113] => stdClass Object ( [title] => text )
    [114] => stdClass Object ( [title] => text text text )
    [115] => stdClass Object ( [title] => text text )
    [116] => stdClass Object ( [title] => text )
)

Problem solved.


Say your records are in $records. You can convert it doing:

$newArray = array();
foreach ($records as $record) {
    $id = $record->id;
    unset($record->id);
    $newArray[$id] = $record;
}

print_r($newArray);
like image 29
NullUserException Avatar answered Apr 11 '26 20:04

NullUserException



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!