Get the specific value of an array, where the other value is "1"?

I have an array that looks like this:

Id = "ADA001" Stock: 15 

There are about 1700 entries in the array that look the same, how would I look for an array for identifier 1 and return the stock?

Edit: I will need to access the stock of each of these 17,000 records

Edit: I got some help from Daniel Centore, he told me to set the primary arrays key for the item id and that it is equal to the fund, but I can’t get it to work.

I am currently retrieving data from a MySQL database and I am storing it in an array, for example:

  $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 does not return anything when I try to repeat my product with the identifier "ADA001"

  echo $myMap["ADA001"]; 

Also, when I do "count ($ mymap)", he says that his 2 entries are big, when he should be bigger than that?

thanks for the help

+5
source share
3 answers

I would use array_filter . Return the comparison result.

 $results = array_filter($targetArray, function($el) { return $el === 1; }); 
+3
source

Edit: Now that it has become clear that the OP wants to query thousands of objects, the correct way to do this is to make the Id the map key in PHP, like this:

 $myMap = []; foreach($array as $item) { $myMap[$item['Id']] = $item['Stock']; } 

Now that you want to access element "12", just use $myMap['12'] .

The reason this happens faster is due to something called algorithmic complexity. You should read about Big-O notation for more information. In fact, the first operation here is of order n , and then the cycle through each of the elements that exit is of order n*log(n) , so the end result is of order n*log(n) , which is the best you can do without additional information. However, if you were only accessing one element, simply accessing that one element through MySQL would be better because it would be of the order of log(n) , which is faster.

Edit 2: Also note that if you need to access multiple fields (i.e. not just stock), you can do the following:

 $myMap = []; foreach($array as $item) { $myMap[$item['Id']] = $item; } 

And just access element 12, for example: $myMap['12']['stock'] or its name: $myMap['12']['name'] .

+1
source

You would do something like that.

 $newArray=[]; foreach($array as $item){ if($item['Id'] === 1){ $newArray[] = $item; } } $stockArray = array_column($newArray,'Stock'); 
0
source

Source: https://habr.com/ru/post/1247044/


All Articles