Php calls

$var - 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 )
)

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

For example, if we call $var['114']['title], he should givetext text text

+3
source share
3 answers

Why don't you create 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 )
)

The problem is resolved.


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

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

print_r($newArray);
+3
source

You can not.

You can create a new array with an identifier as keys, after which you can quickly access the header or loop through the array every time you need to find an identifier.

+6
source

If I understood you correctly, 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'];
?>
+1
source

Source: https://habr.com/ru/post/1758404/


All Articles