Thursday, April 28, 2011

PHP calling tree objects

$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

Thanks.

From stackoverflow
  • 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.

    Happy : looping each time seems not a good idea for performace.
    Gordon : @Ignatz yeah, but that's not Sjoerd's fault. He's just saying it like it is. You cannot omit the array index to get to the stdObject properties without any additional code.
    Sjoerd : I don't know how big your dataset is, but it is usually better to worry about performance when you really have a problem. If you search linearly for 50 items in an array with 100 items, this takes in the order of 1 millisecond. Is your user going to notice that? First solve the problem, then find the hotspots and optimize them.
  • 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);
    
    Happy : CMS creates this array. Question is updated.
    NullUserException : @Ignatz And said CMS doesn't provide a better way to access data?
    NullUserException : @Ignatz answer's been updated
  • If I have understood you right, then here is my example:

    <?php
    // This is your first Array
    $var = array();
    
    // And here some stdClass Objects in this Array
    $var[] = (object) array( 'ID' => 113, 'title' => 'text' );
    $var[] = (object) array( 'ID' => 114, 'title' => 'text text text' );
    $var[] = (object) array( 'ID' => 115, 'title' => 'text text' );
    $var[] = (object) array( 'ID' => 116, 'title' => 'text' );
    
    // Now here the new Array
    $new_var = array();
    foreach( $var as $k => $v )
    {
        $new_var[$v->ID] = (array) $v;
    }
    
    // Now you can use $new_var['113']['title'] and so on
    echo $new_var['113']['title'];
    ?>
    
    NullUserException : What if the records have more properties (ie: `'title' => 'something', 'date' => 2009-02-30)`?
    Happy : thanks man, looks good

0 comments:

Post a Comment