您好我有一个$_SESSION["product"]
数组,$_SESSION["product"]
print_r
输出是:
Array
(
[0] => Array
(
[id] => 152
[name] => 0
[total] => 3
)
[1] => Array
(
[id] => 343
[name] => 0
[total] => 5
)
[2] => Array
(
[id] => 799
[name] => 0
[total] => 7
)
)
我想搜索id时输出并找到主键例如;当我写799时,输出为2或
$_SESSION["product"][2]
答案 0 :(得分:0)
只需循环并检查ID。例如:
$search = 799;
foreach( $products as $key => $product ) {
if( $product[ 'id' ] == $search ) {
$item = $product;
break;
}
}
print_r( $product );
这是未经测试的btw。这将打印出与id匹配的项目。如果您只想使用密钥,请改用它。
$item = $key;
答案 1 :(得分:0)
一个简单的foreach循环就可以做到这一点。当你点击预期的id
时,返回数组记录的密钥。
$search_for = 799;
foreach($_SESSION["product"] as $key => $data) {
if($data['id'] == $search_for) {
$result = $key;
break;
}
}
if($result) {
echo 'Result is: ' . $result;
} else {
echo 'No match';
}
答案 2 :(得分:0)
尚未测试,但应该有效:
$search = 799; // id to search
foreach($_SESSION["product"] as $key => $array) // Look through session array
{
if($array["id"] == $search) // Found your id
{
$output = $key; // Set id to variable
break; // Exit loop
}
}
echo $output; // Your output
答案 3 :(得分:0)
试试这个
function getIndex($name, $array){
foreach($array as $key => $value){
if(is_array($value) && $value['id'] == $name)
return $key;
}
return null;
}
$array = Array(
array(
'id' => 152,
'name' => 0,
'total' => 3
),
array(
'id' => 152,
'name' => 0,
'total' => 3
),
array(
'id' => 799,
'name' => 0,
'total' => 7
),
);
print_r('<pre>');
print_r($array);
echo getIndex(799, $array);
答案 4 :(得分:0)
array_search()
$i=0;
foreach($arr as $val_arr)
{
$key = array_search(799,$val_arr);
if(!empty($key))
{
echo $i; //"prints" 2
}
$i++;
}