获取同一子数组中的值[PHP]
我有以下数组:获取同一子数组中的值[PHP],php,arrays,Php,Arrays,我有以下数组: array(2) { [0]=> array(2) { ["EAN"]=> string(13) "1234567890123" ["Price"]=> string(5) "99.00" } [1]=> array(2) { ["EAN"]=> string(13) "2234567890123" ["Price"]=> string(6) "199.00"
array(2) {
[0]=>
array(2) {
["EAN"]=>
string(13) "1234567890123"
["Price"]=>
string(5) "99.00"
}
[1]=>
array(2) {
["EAN"]=>
string(13) "2234567890123"
["Price"]=>
string(6) "199.00"
}
}
我想:
1) 使用EAN值查找其中一个子数组
2) 并返回此特定EAN的相关价格
例如,函数getPrice('2234567890123')应该返回199.00
getPrice函数的代码应该是什么?您可以使用以下代码:
<?php
$array = array(
"0"=>
array(
"EAN"=>"1234567890123",
"Price"=>"99.00"
),
"1"=>
array (
"EAN"=>"2234567890123",
"Price"=>"199.00"
)
);
$key = array_search('1234567890123', array_column($array, 'EAN'));
echo $array[$key]['Price'];
?>
您可以使用此代码实现所需的输出
//getPrice method which accepts two parameters $products array and $ean number
function getPrice($products,$ean){
//iterate $products array to get its elements
foreach($products as $product){
//if $procust arrays element EAN matches with $ean number we provide
if($product['EAN'] == $ean){
//than return its price
return $product['Price'];
}
}
}
//products array
$products = array(
'0'=>
array(
'EAN'=>'1234567890123',
'Price'=>'99.00'
),
'1'=>
array (
'EAN'=>'2234567890123',
'Price'=>'199.00'
)
);
//EAN value which you need to pass and get its corresponding price
$ean = '2234567890123';
//call getPrice function and save the return output value in a $price variable which you can use anywhere
$price = getPrice($products, $ean);
//print the value by echo $price to verify the required output.
echo $price;
我们不会为您编写代码,告诉我们您尝试了什么以及遇到了什么错误。创建一个循环,查找
EAN
的值,然后测试您的条件(如果匹配),然后存储价格。
//getPrice method which accepts two parameters $products array and $ean number
function getPrice($products,$ean){
//iterate $products array to get its elements
foreach($products as $product){
//if $procust arrays element EAN matches with $ean number we provide
if($product['EAN'] == $ean){
//than return its price
return $product['Price'];
}
}
}
//products array
$products = array(
'0'=>
array(
'EAN'=>'1234567890123',
'Price'=>'99.00'
),
'1'=>
array (
'EAN'=>'2234567890123',
'Price'=>'199.00'
)
);
//EAN value which you need to pass and get its corresponding price
$ean = '2234567890123';
//call getPrice function and save the return output value in a $price variable which you can use anywhere
$price = getPrice($products, $ean);
//print the value by echo $price to verify the required output.
echo $price;