Looking for an element in an array in PHP - php
I don't know if I'm managing this array in the best way.
The array I have is this:
$bass = $_POST['bass'];
$selected_scale = $_POST['scale'];
$major_scales = array
(
array("C","D","E","F","G","A","B","C","D","E","F","G","A","B",),
array("C#","D#","E#","F#","G#","A#","B#","C#","D#","E#","F#","G#","A#","B#",),
array("Db","Eb","F","Gb","Ab","Bb","C","Db","Eb","F","Gb","Ab","Bb","C",),
array("D","E","F#","G","A","B","C#","D","E","F#","G","A","B","C#"),
array("D#","E#","F##","G#","A#","B#","C##","D#","E#","F##","G#","A#","B#","C##"),
array("Eb","F","G","Ab","Bb","C","D","Eb","F","G","Ab","Bb","C","D"),
array("E","F#","G#","A","B","C#","D#","E","F#","G#","A","B","C#","D#"),
array("E#","F##","G##","A#","B#","C##","D##","E#","F##","G##","A#","B#","C##","D##"),
array("Fb","Gb","Ab","Bbb","Cb","Db","Eb","Fb","Gb","Ab","Bbb","Cb","Db","Eb"),
array("F","G","A","Bb","C","D","E","F","G","A","Bb","C","D","E"),
array("F#","G#","A#","B","C#","D#","E#","F#","G#","A#","B","C#","D#","E#"),
array("Gb","Ab","Bb","Cb","Db","Eb","F","Gb","Ab","Bb","Cb","Db","Eb","F"),
array("G","A","B","C","D","E","F#","G","A","B","C","D","E","F#"),
array("G#","A#","B#","C#","D#","E#","F##","G#","A#","B#","C#","D#","E#","F##"),
array("Ab","Bb","C","Db","Eb","F","G","Ab","Bb","C","Db","Eb","F","G"),
array("A","B","C#","D","E","F#","G#","A","B","C#","D","E","F#","G#"),
array("A#","B#","C##","D#","E#","F##","G##","A#","B#","C##","D#","E#","F##","G##"),
array("Bb","C","D","Eb","F","G","A","Bb","C","D","Eb","F","G","A"),
array("B","C#","D#","E","F#","G#","A#","B","C#","D#","E","F#","G#","A#"),
array("B#","C##","D##","E#","F##","G##","A##","B#","C##","D##","E#","F##","G##","A##"),
array("Cb","Db","Eb","Fb","Gb","Ab","Bb","Cb","Db","Eb","Fb","Gb","Ab","Bb")
);
$bass is a string, like the one inside the arrays. The $selected_scale is just a number.
What I'm trying to do is to find the $bass in one of those array in the position of $selected_scale. Basically, $bass = $major_scales[$selected_scale]. Therefore I want to create a loop in order to get the elements after that.
But I don't know how to manage in this case the situation. I've looked everything in internet and try various solutions without success. I'd like to know how can I do it. Thanks
Try to use next loop:
// if value exists in mentioned index
if (in_array($bass,$major_scales[$selected_scale])){
// index of that value in that array
$tmp_ind = array_search($bass,$major_scales[$selected_scale]);
// length of the array
$len = count($major_scales[$selected_scale]);
// store values after this value
$res = [];
for ($i=$tmp_ind;$i<$len;$i++){
$res[$i] = $major_scales[$selected_scale][$i];
}
}
print_r($res);
Demo1
If you need to find value by index $selected_scale in one of these arrays and also store values after this position:
foreach($major_scales as $ar){
if ($ar[$selected_scale] == $bass){
// length of the array
$len = count($ar);
// store values after this value
$res = [];
for ($i=$selected_scale;$i<$len;$i++){
$res[$i] = $ar[$i];
}
}
}
print_r($res);
Demo2
Related
what should I use instead of array_unique in php?
I am getting duplicate data in an array and that data is storing in my DB. I am using array_unique to refine the duplicate data but it is not working. Please tell me is there any other way to make data unique and store in DB this way. if (preg_match($keywords, $links[$i]->href)) { if (filter_var($links[$i]->href, FILTER_VALIDATE_URL) !== false) { array_push($mainNews, $links[$i]->href); } } return (array_unique($mainNews)); Error I am getting: Undefined array key 1 at C:\xampp\htdocs\pacra-crawlers\modules\crawlers\services\MainNewsRepository.php:46 for ($i = 0; $i < count($mainNewsLinks); $i++) { $mainNews = new MainNews(); $mainNews->newspaper_id = $this->newspaperId; $mainNews->sector_id = $sectorId; $mainNews->url = $mainNewsLinks[$i]; $mainNews->save(); } return ['status' => true]; } C:\xampp\htdocs\pacra-crawlers\modules\crawlers\services\MainNewsRepository.php:46 Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Undefined array key 1", "C:\xampp\htdocs\pacra-crawlers\modules\crawlers\services\MainNewsRepo sitory.php")
array_unique is working however although it is removing duplicates it is maintaining the same keys i.e. If you had the following items in an array with position/key value 0 a 1 a 2 b array_unique would return position/key value 0 a 2 b which is why you are getting the Undefined array key when looping through the array based on the incrementing index $i. Based on your sample you could use a foreach loop since you are only interested in the value eg foreach($mainNewsLinks as $mainNewsLink) { $mainNews = new MainNews(); $mainNews->newspaper_id = $this->newspaperId; $mainNews->sector_id = $sectorId; $mainNews->url = $mainNewsLink; $mainNews->save(); } If you would like to continue indexing or iterating through each element based on an index, you could use array_values in your return eg return array_values(array_unique($mainNews)); from your function to reset the array keys to incrementing indexes
Search multi-dimesional array and return specific value
Hard to phrase my question, but here goes. I've got a string like so: "13,4,3|65,1,1|27,3,2". The first value of each sub group (ex. 13,4,3) is an id from a row in a database table, and the other numbers are values I use to do other things. Thanks to "Always Sunny" on here, I'm able to convert it to a multi-dimensional array using this code: $data = '13,4,3|65,1,1|27,3,2'; $return_2d_array = array_map ( function ($_) {return explode (',', $_);}, explode ('|', $data) ); I'm able to return any value using echo $return_2d_array[1][0]; But what I need to be able to do now is search all the first values of the array and find a specific one and return one of the other value in i'ts group. For example, I need to find "27" as a first value, then output it's 2nd value in a variable (3).
You can loop through the dataset building an array that you can use to search: $data = '13,4,3|65,1,1|27,3,2'; $data_explode = explode("|",$data); // make array with comma values foreach($data_explode as $data_set){ $data_set_explode = explode(",",$data_set); // make an array for the comma values $new_key = $data_set_explode[0]; // assign the key unset($data_set_explode[0]); // now unset the key so it's not a value.. $remaining_vals = array_values($data_set_explode); // use array_values to reset the keys $my_data[$new_key] = $remaining_vals; // the array! } if(isset($my_data[13])){ // if the array key exists echo $my_data[13][0]; // echo $my_data[13][1]; // woohoo! } Here it is in action: http://sandbox.onlinephpfunctions.com/code/404ba5adfd63c39daae094f0b92e32ea0efbe85d
Run one more foreach loop like this: $value_to_search = 27; foreach($return_2d_array as $array){ if($array[0] == $value_to_search){ echo $array[1]; // will give 3 break; } } Here's the live demo.
array_key_exist() with array as key
I'm trying to check if in an array there is any value of another array. The function array_key_exist() looks like what I'm searching for, but I don't understand how to give the key value at the function as an array. Here's the code: $risultato_query_controllo_numero = mysql_query($query_controllo_numero); $voucher_esistenti = array(); while(($row = mysql_fetch_assoc($risultato_query_controllo_numero))) { $voucher_esistenti[] = $row['numero']; } Which populates the first array with numbers: $voucher = range($numero, $numero + $quantita); Which populates the second array with numbers. What I need to do now is to check if any of the value in $voucher is present in $voucher_presenti.
You can use the array_intersect function: $overlap = array_intersect($voucher, $voucher_presenti); You can find more examples in the documentation.
You could use the in_array() function to get the result you are looking for. $arrayOne = range(1, 10); $arrayTwo = range(5, 15); foreach ($arrayOne as $value) { if (in_array($value, $arrayTwo)) { echo 'value '.$value.' is in the first and second array.<br />'; } } Resources in_array() - Manual
in_array could be a good solution for your need, for example you can assign $voucher_esistenti only when you have a new value in the sql row. $risultato_query_controllo_numero=mysql_query($query_controllo_numero); $voucher_esistenti=array(); while(($row = mysql_fetch_assoc($risultato_query_controllo_numero))){ if(!in_array($row['numero'], $voucher_esistenti) { $voucher_esistenti[] = $row['numero']; } } // this solution isn't optimal, because you will check subarrays with each new value There's a better way to achieve that, by using a hashmap which has a complexity of O(1) ( best complexity :) ) $risultato_query_controllo_numero=mysql_query($query_controllo_numero); $voucher_esistenti=array(); while(($row = mysql_fetch_assoc($risultato_query_controllo_numero))){ // here is what we changed, instead of key = value, we actually append keys if(!isset($voucher_esistenti[$row['numero']]) { $voucher_esistenti[$row['numero']] = true; } } /* The second implementation is a lot faster due to the algorithm, but you will have to change the reading of $voucher_esistenti array. */
Find index of value in associative array in php?
If you have any array $p that you populated in a loop like so: $p[] = array( "id"=>$id, "Name"=>$name); What's the fastest way to search for John in the Name key, and if found, return the $p index? Is there a way other than looping through $p? I have up to 5000 names to find in $p, and $p can also potentially contain 5000 rows. Currently I loop through $p looking for each name, and if found, parse it (and add it to another array), splice the row out of $p, and break 1, ready to start searching for the next of the 5000 names. I was wondering if there if a faster way to get the index rather than looping through $p eg an isset type way? Thanks for taking a look guys.
Okay so as I see this problem, you have unique ids, but the names may not be unique. You could initialize the array as: array($id=>$name); And your searches can be like: array_search($name,$arr); This will work very well as native method of finding a needle in a haystack will have a better implementation than your own implementation. e.g. $id = 2; $name= 'Sunny'; $arr = array($id=>$name); echo array_search($name,$arr); Echoes 2 The major advantage in this method would be code readability.
If you know that you are going to need to perform many of these types of search within the same request then you can create an index array from them. This will loop through the array once per index you need to create. $piName = array(); foreach ($p as $k=>$v) { $piName[$v['Name']] = $k; } If you only need to perform one or two searches per page then consider moving the array into an external database, and creating the index there.
$index = 0; $search_for = 'John'; $result = array_reduce($p, function($r, $v) use (&$index, $search_for) { if($v['Name'] == $search_for) { $r[] = $index; } ++$index; return $r; }); $result will contain all the indices of elements in $p where the element with key Name had the value John. (This of course only works for an array that is indexed numerically beginning with 0 and has no “holes” in the index.) Edit: Possibly even easier to just use array_filter, but that will not return the indices only, but all array element where Name equals John – but indices will be preserved: $result2 = array_filter($p, function($elem) { return $elem["Name"] == "John" ? true : false; }); var_dump($result2); What suits your needs better, resp. which one is maybe faster, is for you to figure out.
Assign values to an associated array in a loop
I am having a difficult time creating an associated array and assigning a value to the key. I have two arrays (tech_pay and tech_scans) and I am doing a simple calculation using their values and I want to create a new array called tech_per_scan but I keep getting an array with the key automatically created starting at 0. $tech_per_scan = array(); foreach($tech_pay as $key=>$value) { $pay_per_scan = $tech_pay[$key]['tot_pay']/$tech_scans[$key]['scans'];//calculate the payment per scan $tech_per_scan[] = array('id'=>$key,'pay_per_scan'=>$pay_per_scan); }
This line $tech_per_scan[] = array('id'=>$key,'pay_per_scan'=>$pay_per_scan); will add an element to you array and it will start with 0 as its index, because you did not specify its key. Similar to array_push It should be $tech_per_scan[$id]
$tech_per_scan[$id] = $pay_per_scan;
you should set value for new array like this : $tech_per_scan[$key] = $pay_per_scan ; Full code is : $tech_per_scan = array(); foreach($tech_pay as $key=>$value) { $pay_per_scan = $tech_pay[$key]['tot_pay']/$tech_scans[$key]['scans'];//calculate the payment per scan $tech_per_scan[$key] = $pay_per_scan ; }