开发者

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])

开发者_如何学Go

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


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.


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);


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'];
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜