开发者

Getting a value from an array in PHP

I'm a bit confused with the array that I have to work with. The following array:

print_r($myArray);

returns the following:

Array (
    [0] => stdClass Object (
        [id] => 88
        [label] => Bus
    )
    [1] => stdClass Object (
        [id] => 89
        [label] => Bike
    )
    [2] => stdClass Object (
        [id] => 90
        [label] => Plane
    )
    [3] => stdClass Object (
        [id开发者_JS百科] => 91
        [label] => Submaine
    )
    [4] => stdClass Object (
        [id] => 92
        [label] => Boat
    )
    [5] => stdClass Object (
        [id] => 93
        [label] => Car
    )
    [6] => stdClass Object (
        [id] => 94
        [label] => Truck
    )
) 

How do I get the label value, say, "Submaine", if I have the $id = 91?


This will get you the object(s) you seek:

$objects = array_filter($myArray, function($item){ return $item->id == 91 })

Then it's just a matter of getting the attribute of the object that you want.


You're going to have to loop through the array, I think.

$value = '';
foreach ($myArray as $el) {
    if ($el->id === 91) { // or other number
        $value = $el->label;
        break;
    }
}

The label is now contained in $value.


Benchmark values vs AJ's version for 1000000 iterations (see source):

lonesomeday: 1.8717081546783s
AJ: 4.0924150943756s
James C: 2.9421799182892s


What you have there is an array of objects. I'd suggest re-keying the array by id like this:

$new = array();
foreach($array as $obj) {
    $new[ $obj->id ] = $new[ $obj->label ];
}

Now you've got a nice associative array that you can use normally e.g. echo $new[92] will echo "Boat"

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜