我有以下数组:
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的代码应该是什么?
答案 0 :(得分:1)
您可以使用此代码:
<?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'];
?>
答案 1 :(得分:0)
/**
* this generates a multi dimensional array of products
* a multi dimensional array means arrays within arrays
* so to access the inner array (EAN => '12345...')
* we need to loop through the outer array (0 => [EAN => '12345...'])
*/
$products_array = [
0 => [
'EAN' => '1234567890123',
'Price' => '99.00',
],
1 => [
'EAN' => '2234567890123',
'Price' => '199.00',
],
];
/**
* here is the function, it takes two arguments
* the products array and the ean number you want to get the price of
*/
function getPrice($products_array, $ean)
{
// we loop through the array using a foreach loop.
foreach ($products_array as $key => $product) {
// now product is just a single level array
// we can access the ean by
// typing $product['EAN'] and the Price by
// typing $product['Price']
if ($product['EAN'] === $ean) {
return $product['Price'];
// When there is a match the function returns the result and exits the loop
}
}
}
/**
* here we are calling the function an giving it two things
* 1 - the array we want to loop through and
* 2 - the EAN number that we want to get the price of
* don't forget to echo the output!
*/
echo getPrice($products_array, '2234567890123');
答案 2 :(得分:0)
您可以使用此代码来实现所需的输出。
//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;