Page 1 of 1
Noob: Searching a multidimensional array
Posted: Wed Feb 02, 2011 6:57 am
by Wilbo
Hi,
Lets say I have an array called $productPrices into which I'm putting values in pairsto represent a product code and a price:
Code: Select all
$productPrices = array();
$productPrices[] = array("AB001"=>"10",);
$productPrices[] = array("AB002"=>"23",);
$productPrices[] = array("AB003"=>"14",);
etc
What I want to do is search through the array for a certain ProductCode and return the corresponding Price.
And I know that each product code is unique, so I want it to break out once its found the ProductCode.
I've read and re-read the manual and tried dozen things but I just can't figure it out!
Thanks in advance!
Re: Noob: Searching a multidimensional array
Posted: Wed Feb 02, 2011 7:18 am
by Peter Kelly
Try
Code: Select all
<?php
$product_code = "AB001";
foreach($productPrices as $id){
if($productPrices[$id]['0'] == $product_code){
echo "Price: " . $productPrices[$id]['0'];
break(1);
}
}
?>
I'm not sure if it will work it was just quickly while I was in work.
Re: Noob: Searching a multidimensional array
Posted: Wed Feb 02, 2011 7:24 am
by klevis miho
Code: Select all
<?php
$productPrices = array();
$productPrices[] = array("AB001"=>"10");
$productPrices[] = array("AB002"=>"23");
$productPrices[] = array("AB003"=>"14");
//product code that will be searched
$productCode = 'AB003';
foreach($productPrices as $productPrice) {
foreach($productPrice as $pCode => $price) {
if($pCode == $productCode) {
echo $productPrice[$pCode];
}
}
}
?>
Re: Noob: Searching a multidimensional array
Posted: Wed Feb 02, 2011 7:56 am
by Wilbo
Thanks for the answers but I made an error in my original question, the array that I have is actually this:
$productPrices = array();
$productPrices[] = array("productCode"=>"AB001", "price"=>"10");
$productPrices[] = aarray("productCode"=>"AB002", "price"=>"10");
$productPrices[] = array("productCode"=>"AB003", "price"=>"10");
Sorry to have wasted anyone's time.
Any ideas about how to search this array?
Re: Noob: Searching a multidimensional array
Posted: Wed Feb 02, 2011 8:02 am
by Peter Kelly
Wilbo wrote:Thanks for the answers but I made an error in my original question, the array that I have is actually this:
$productPrices = array();
$productPrices[] = array("productCode"=>"AB001", "price"=>"10");
$productPrices[] = array("productCode"=>"AB002", "price"=>"10");
$productPrices[] = array("productCode"=>"AB003", "price"=>"10");
Sorry to have wasted anyone's time.
Any ideas about how to search this array?
Code: Select all
<?php
$product_code = "AB001";
foreach($productPrices as $products){
if($products[productCode] == $product_code){
echo "Price: " . $products[price];
break(1);
}
}
?>
Re: Noob: Searching a multidimensional array
Posted: Wed Feb 02, 2011 8:07 am
by Wilbo
Thanks Peter, that works a treat!