数组看起来像:
[0] => stdClass Object
(
[ID] => 420
[name] => Mary
)
[1] => stdClass Object
(
[ID] => 10957
[name] => Blah
)
...
我有一个整数变量$v。
我如何选择一个数组条目,其中有一个对象的ID属性有$v值?
我使用某种Java键映射来实现这一点。
如果你这样做,你不需要每次都循环遍历你的对象数组。
<?php
//This is your array with objects
$object1 = (object) array('id'=>123,'name'=>'Henk','age'=>65);
$object2 = (object) array('id'=>273,'name'=>'Koos','age'=>25);
$object3 = (object) array('id'=>685,'name'=>'Bram','age'=>75);
$firstArray = Array($object1,$object2);
var_dump($firstArray);
//create a new array
$secondArray = Array();
//loop over all objects
foreach($firstArray as $value){
//fill second key value
$secondArray[$value->id] = $value->name;
}
var_dump($secondArray);
echo $secondArray['123'];
输出:
array (size=2)
0 =>
object(stdClass)[1]
public 'id' => int 123
public 'name' => string 'Henk' (length=4)
public 'age' => int 65
1 =>
object(stdClass)[2]
public 'id' => int 273
public 'name' => string 'Koos' (length=4)
public 'age' => int 25
array (size=2)
123 => string 'Henk' (length=4)
273 => string 'Koos' (length=4)
Henk