在php中如何在二维数组中按值搜索索引
我有一个函数来获取courier的描述,所有关于courier的记录都存储在在php中如何在二维数组中按值搜索索引,php,Php,我有一个函数来获取courier的描述,所有关于courier的记录都存储在$couriers中$courier是二维数组,因为它包含表courier的所有行 [ { "id":"1", "name":"DTDC", "description":"Automatically inserted by application ", "bloked":"false" }, { "id":"2", "name":"Ecomm", "description":"Nothing", "bloked":"fa
$couriers
中$courier是二维数组,因为它包含表courier的所有行
[
{
"id":"1",
"name":"DTDC",
"description":"Automatically inserted by application ",
"bloked":"false"
},
{
"id":"2",
"name":"Ecomm",
"description":"Nothing",
"bloked":"false"
},
{
"id":"3",
"name":"MarginPrice",
"description":"Local only",
"bloked":"false"
}
]
现在,我得去拿身份证上的快递员的说明。对于
为此,我必须知道这些记录的索引。。我试过了
使用数组搜索,但“困难时间”。所以,我请求帮助给出一个想法
要知道数组中记录的索引
试试这种简单易用的方法
您的$courier变量已更改以便于查找,它包含如下数组:
Array
(
[1] => Array
(
[id] => 1
[name] => DTDC
[description] => Automatically inserted by application
[bloked] => false
)
[2] => Array
(
[id] => 2
[name] => Ecomm
[description] => Nothing
[bloked] => false
)
[3] => Array
(
[id] => 3
[name] => MarginPrice
[description] => Local only
[bloked] => false
)
)
用这个
$jsonArray = '[
{
"id":"1",
"name":"DTDC",
"description":"Automatically inserted by application ",
"bloked":"false"
},
{
"id":"2",
"name":"Ecomm",
"description":"Nothing",
"bloked":"false"
},
{
"id":"3",
"name":"MarginPrice",
"description":"Local only",
"bloked":"false"
}
]';
$arrData = json_decode($jsonArray,true);
print_r(searchForId('3',$arrData,'id'));
function searchForId($id, $array,$field) {
foreach ($array as $key => $val) {
if ($val[$field] === $id) {
return $val['description'];
}
}
return null;
}
您知道$courier变量不是数组,它是一个json字符串,所以先对它进行dcode,然后在php数组中将其转换为
$couriers = json_decode($couriers,true);
现在,您的函数可以定义如下,使用
下面是以数组_映射为界的函数
function getAllCourierId($arr)
{
return $arr['id'];
}
你的数组是什么样子的?将你的样本数组添加到问题中你好,欢迎来到SO,我强烈建议你看一下,以便更好地了解SO的工作原理,以及如何编写你的问题,从而获得尽可能最好的答案:)现在,我在问题中包括了数组格式,我有..@Rashmingh检查答案,以便使用id从数组中轻松找到,您也可以仅返回说明。。。。。。。。祝你好运
$couriers = json_decode($couriers,true);
function getCourierDescriptionById($id)
{ global $couriers;
$args=func_num_args();
if($couriers==null)
{
loadCourier($id);
}
$index=array_search($id,array_map("getAllCourierId",$couriers));
return isset($couriers[$index]['description'])?
$couriers[$index]['description']:null;
}
function getAllCourierId($arr)
{
return $arr['id'];
}