简体   繁体   English

根据另一个值从数组中获取特定数据

[英]Get Specific Data From Array, Based On Another Value

I have an array that outputs these values: 我有一个输出这些值的数组:

Array ( 
    [0] => stdClass Object ( 
        [ID] => 6585
        [COLOR] => red 
        [Name] => steve
        ) 
    [1] => stdClass Object ( 
        [ID] => 5476 
        [COLOR] => blue 
        [Name] => sol
        ) 
    [2] => stdClass Object ( 
        [ID] => 7564 
        [COLOR] => yellow 
        [Name] => jake 
        ) 
    [3] => stdClass Object ( 
        [ID] => 3465 
        [COLOR] => green 
        [Name] => helen 
        ) 
    )

Now, I will know the ID of the person, and I need the get the COLOR value for that specific value set. 现在,我将知道该人的ID,并且需要获取该特定值集的COLOR值。 How is this best achieved please? 请问如何最好地做到这一点?

Something like this: 像这样:

function getColorById($arr, $id){
    foreach($arr as $item){
        if ($item->ID == $id)
            return $item->COLOR;
    }
    return "blah!";
}

Use like echo getColorById($arr, 3465); 使用类似echo getColorById($arr, 3465);

EDIT : The way you have the data leads to slowing down access times. 编辑 :您拥有数据的方式会导致访问时间变慢。 A better suggestion is to (since it seems ID is unique), you'd rather have that as the key to your array. 一个更好的建议是(因为ID似乎是唯一的),所以您最好将其作为数组的键。 You have integer indices to it, now. 您现在有整数索引。 Construct the array (unless you are receiving it from some area beyond what you have control over) something like the below: 构造数组(除非您从无法控制的某个区域接收它)如下所示:

$arr = array();
$arr["ID_4634"] = <object>;

You probably want change the way you are storing it up for faster access. 您可能想要更改存储方式,以便更快地访问。

With the current format, you will need to loop through the elements and compare colors until you find a match. 使用当前格式,您将需要遍历元素并比较颜色,直到找到匹配项。

for($i=0;$i<count($array);$i++){
  if($array[$i]['ID'] == $id)
    return $array[$i]['COLOR']
}

alternatively, store it with the ID's as the keys. 或者,将其与ID一起存储为密钥。

$users = array();
$count = count($arr);
for ($i = 0; $i < $count; $i++) {
    $users[$arr[$i]['ID']] = array(
        'Name' => $arr[$i]['Name'],
        'COLOR' => $arr[$i]['COLOR']
    );
}
echo $users[$id]['COLOR'];

where $arr represents the array you outputted in your initial post and $id is the id of the person who's color you're trying to access. 其中$ arr代表您在初始帖子中输出的数组,而$ id是您尝试访问的有色人的ID。 You can also then get their name by using 您还可以通过使用获得他们的名字

echo $users[$id]['Name'];

IDTry below : ID尝试以下:

for($i=0; $i<count($array); $i++)
{
  if($array[$i]['ID'] == $id)
    return $array[$i]['COLOR'];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM