Reputation: 161
I have an array that looks like this:
Id = "ADA001"
Stock: 15
The array has about 1700 records that looks the same, how would I search the array for the ID 1 and return the stock?
Edit: I will need to access the stock of each one of these 17000 records
Edit: I have been getting some help from Daniel Centore, he told me to set an arrays primary key to the id of the item and that it is equal to the stock, but I can't get it to work.
I am currently getting the data from an MySQL database and I store it in an array, like so:
$data[] = array();
$getdisposabletest = mysqli_query($connect, "Select id, disposable FROM products");
while ($z = mysqli_fetch_array($getdisposabletest)) {
$data = $z;
}
Now when I use Daniels code that looks like this:
$myMap = [];
foreach($data as $item) {
$myMap[$item['id']] = $item['disposable'];
}
It doesn't return anything when I try to echo my product with the ID "ADA001"
echo $myMap["ADA001"];
Also when I do "count($mymap)" it says its 2 records big, when it should be muuuch larger than that?
Thanks for help
Upvotes: 6
Views: 808
Reputation: 3349
Edit: Now that it has been made clear that the OP wants to query from thousands of items, the correct way to do this is to make the Id
the key to a map in PHP, like this:
$myMap = [];
foreach($array as $item) {
$myMap[$item['Id']] = $item['Stock'];
}
Now, whenever you want to access item '12', simply use $myMap['12']
.
The reason this is faster is because of something called algorithmic complexity. You should read about Big-O notation for more info. Essentially, the first operation here is on the order of n
and then looping through each of the items that comes out is on the order of n*log(n)
, so the final result is on the order of n*log(n)
which is the best you'll be able to do without more information. However, if you were only accessing one element, just accessing that one element via MySQL would be better because it would be on the order of log(n)
, which is faster.
Edit 2: Also notice that if you were to access mutliple fields (ie not just the stock) you could do the following:
$myMap = [];
foreach($array as $item) {
$myMap[$item['Id']] = $item;
}
And simply access item 12's stock like this: $myMap['12']['stock']
or its name like this: $myMap['12']['name']
.
Upvotes: 1
Reputation: 4880
I would use array_filter. Return the result of a comparitor.
$results = array_filter($targetArray, function($el) {
return $el === 1;
});
Upvotes: 3
Reputation: 3256
You would do something like this.
$newArray=[];
foreach($array as $item){
if($item['Id'] === 1){
$newArray[] = $item;
}
}
$stockArray = array_column($newArray,'Stock');
Upvotes: 0