PHP通过从另一个数组传递值而不使用foreach从数组中获取值
I've two arrays $products
and $id_n_qty
$id_n_qty array contains Product id and its quantity where $products array contains all products with their IDs and name.
$products = array(1=>"Shampoo",2=>"Towel");
$id_n_qty = array(1=>3);
My question is how can i get the Product name when i have the $id_n_qty
with me without using php foreach
?
Thanks
我有两个数组 我的问题是如何在获取产品名称时 我没有使用 谢谢 p>
div> $ products code>和
$ id_n_qty code> $ id_n_qty数组包含产品ID及其数量,其中$ products数组包含所有带有ID和名称的产品。 p>
$ products = array(1 =>“Shampoo”,2 =>“毛巾”);
$ id_n_qty = array(1 => 3);
code> pre>
php foreach code>,我有
$ id_n_qty code>? p>
Try with array_keys
like
$key_val = array_keys($id_n_qty);
echo $products[$key_val[0]];
Considering that you have only single array in the $id_n_qty
.
If you are saying that the key for $id_n_qty
matches the keys in $products
, you simply need to investigate the key values.
$product_names = array_intersect_key($products, $id_n_qty);
Note that this gives you the product names for all key values that are in $id_n_qty, thus the $product_names variable is an array.
If like you said you have single array, you can get the ID like this:
// Getting ID
$id = key(reset($id_n_qty));
// Getting Quantity
$qty = $id_n_qty[$id];
But I must say this is not an elegant way to do it. You could get the id and quantity as seperate item then it will be more elegant to get it:
// First item is ID and second item is Quantity
$id_n_qty = array(1, 3);
// Getting ID and Quantity:
list($id, $quantity) = $id_n_qty;
As you see it is easy and looking good. If you can convert the array to this that is.