从多维数组中获取“唯一ID”的信息

时间:2012-12-07 05:58:58

标签: php arrays

我有一个具有这种结构的数组:

Array
(
    [mysite] => Array
        (
            [0] => Array
                (
                    [0] => uniqueid
                    [1] => brand
                    [2] => horsepower
                    [3] => topspeed
                )

            [1] => Array
                (
                    [0] => uniqueid
                    [1] => brand
                    [2] => horsepower
                    [3] => topspeed
                )

            [2] => Array
                (
                    [0] => uniqueid
                    [1] => brand
                    [2] => horsepower
                    [3] => topspeed
                )
        )
)

每辆车都有“独特”,其次是品牌,马力等等。

如果我想获取随机车的信息,我会这样做:

$rkey = array_rand($sites['mysite'], 1); // get a random key
$car_info = $myarray['mysite'][$rkey];

您对如何使用某个“uniqueid”获取信息有任何想法

$car_info = "get the information of a car with a certain uniqueid";

泰!

3 个答案:

答案 0 :(得分:0)

试,

在for循环中传递唯一ID,您将得到奇怪的结果 它可能对你有帮助,

$array = array(

  0   => Array
            (
                0 => 'uniqueid0',
                1 => 'brand',
                2 => 'horsepower',
                3 => 'topspeed',
            ),
  1   => Array
            (
                0 => 'uniqueid1',
                1 => 'brand',
                2 => 'horsepower',
                3 => 'topspeed',
            ),
  2  => Array
            (
                0 => 'uniqueid2',
                1 => 'brand',
                2 => 'horsepower',
                3 => 'topspeed',
            ),
  3  => Array
            (
                0 => 'uniqueid3',
                1 => 'brand',
                2 => 'horsepower',
                3 => 'topspeed',
            ),
);


  foreach($array as $arr){
    if($arr[0] == 'uniqueid2'){
      $result = $arr;
      break;
    }
  }

print_r($ result);

输出:

数组([0] => uniqueid2 [1] =>品牌[2] =>马力[3] =>最高速度)

答案 1 :(得分:0)

$uniqueid = 12345;

foreach ($myarray['mysite'] as $car) {
    if($car[0] == $uniqueid) {
        $car_info = $car;
        break;
    }
}

答案 2 :(得分:0)

如果uniqueid在汽车中是唯一的,那么您可以尝试按如下方式重组阵列

如果可能的话

Array (
    [mysite] => Array
    (
        [uniqueid1] => Array
            (
                [0] => uniqueid1
                [1] => brand
                [2] => horsepower
                [3] => topspeed
            )

        [uniqueid2] => Array
            (
                [0] => uniqueid2
                [1] => brand
                [2] => horsepower
                [3] => topspeed
            )

        [uniqueid3] => Array
            (
                [0] => uniqueid3
                [1] => brand
                [2] => horsepower
                [3] => topspeed
            )
    )
)

这样你可以直接访问汽车的uniqueid,也可以应用随机逻辑

如果不是@Jevgeni Bogatyrjov解决方案效果很好

foreach ($myarray['mysite'] as $car) {
    if($car[0] == $uniqueid) {
        $car_info = $car;
        break;
    }
}