使用array_search多维数组 [英] using array_search for multi dimensional array

查看:333
本文介绍了使用array_search多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在1维数组使用array_search简单

  $阵列=阵列(苹果,香蕉,樱桃);
$ searchValue =樱花;
$键= array_search($ searchValue,$阵列);回声$关键;

但如何对一个关联数组?

  #RaceRecord    [CarID] [ColorID] [位置]
[0] 1 1 3
[1] 2 1 1
[2] 3 2 4
[3] 4 2 2
[4] 5 3 5

例如我想要得到的车,其位置是索引1.如何做到这一点?


解决方案

 函数find_car_with_position($汽车,$位置){
    的foreach($轿车为$指数=> $车){
        如果($车['位置'] == $位置)返回$指数;
    }
    返回FALSE;
}

using array_search in a 1 dimensional array is simple

$array = array("apple", "banana", "cherry");
$searchValue = "cherry";
$key = array_search($searchValue, $array);

echo $key;

but how about an associative array?

    #RaceRecord

    [CarID] [ColorID] [Position]
[0]    1        1         3
[1]    2        1         1
[2]    3        2         4
[3]    4        2         2
[4]    5        3         5

for example i want to get the index of the car whose position is 1. How do i do this?

解决方案

function find_car_with_position($cars, $position) {
    foreach($cars as $index => $car) {
        if($car['Position'] == $position) return $index;
    }
    return FALSE;
}

这篇关于使用array_search多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆