Push item into an array and replace php - php
i need to make an array like this
$privateMsgIdArray = array("idlistener" => $idlistener, "maxMsgId" => $lastMsgId);
I need to replace the maxMsgId to the corresponding idlistener, and if the idlistener that i pass doesn't not exist to create a new entry inside the array.
I am a but confused on how i am going to extract the maxMsgId value corresponding to an idlistener.
In other words i need to pass new values of idlisteners only once, and replace maxMsgId each time that they are not equal to the corresponing idlistener.
If the idlistener field doesn't exist create it (push into array).
I pass old array into a session and new array in the current run.
After the run i i replace them.
I believe this sounds a bit confusing though.
e.g
We have an array like this already:
[15][200]
next call maxMsgId is 210
array should be
[15][210]
next call we have a new listener id with maxMsgId 30
array should be
[15][210]
[16][30]
You should be able to accomplish this with a quick loop:
// your "new" values
$idListener = 15;
$maxMsgId = 210;
// loop over the array to see if it contains the `idlistener` you want
$end = count($privateMsgIdArray);
for ($i = 0; $i < $end; $i++) {
if ($privateMsgIdArray[$i]['idlistener'] == $idListener) {
// we found it! overwrite the `maxMsgId` field
$privateMsgIdArray[$i]['maxMsgId'] = $maxMsgId;
break;
}
}
if ($i == $end) {
// we reached the end of the array without finding the `$idListener`;
// add a new entry =]
$privateMsgIdArray[] = array(
'idlistener' => $idListener,
'maxMsgId' => $maxMsgId
);
}
This is a rather brute-force approach though and, if efficiency is something you're after, it would be wise to create a "cache"-style method of idlistener values and their index in the $privateMsgIdArray array.
For instance:
// key = idlistener, value = index in `$privateMsgIdArray`
$idCache = array(15 => 0, 16 => 1);
// check if the `$idListener` is in the cache
if (!isset($idCache[$idListener])) {
// it's not; add a new entry
$key = count($privateMsgIdArray);
$privateMsgIdArray[$key] = array(
'idlistener' => $idListener,
'maxMsgId' => $maxMsgId
);
// add the new index into the cache
$idCache[$idListener] = $key;
} else {
// it is in the cache; pull the corresponding index and set the `maxMsgId` =]
$privateMsgIdArray[$idCache[$idListener]]['maxMsgId'] = $maxMsgId;
}
Both of the approaches above could be converted into functions to make things "more portable" too.
Related
Restore array items after every iteration in PHP
I am trying to restore all array items after each for loop iteration. This I need to set Laravel validation Rule::notIn($arry) I have an array of station_id generated by cloned input fields. I want to check if all cloned station ids are unique, and so be sure that no repeated station in the metro route. For cloned fields, I am setting up a rule using for a loop by counting cloned items. So the issue is, I want to use `Rule::notIn($stationIds) except the current iteration item id so I can validate by checking the current id is not in the rest of the array items. public function rules() { // getting all input fields value $rStationIds = $this->get('station_id') ... // get the max number of input $counter = $this->getMaxCount($rStationIds, ...); $rules = []; // loop through each item for ($r = 0; $r < $counter; $r++) { unset($rStationIds[$r]); $rules['station_id'][$r] = ['required', 'int', Rule::notIn($rStationIds)]; } ... } The problem in the above code is that when I unset($var) the current item, it never reset back with the original array elements; thus, the last field will have nothing to compare because the array will get empty. I am okay with any other approach as well to check the unique item for the cloned station id fields.
Change your loop to: // loop through each item for ($r = 0; $r < $counter; $r++) { $temp = $rStationIds[$r]; unset($rStationIds[$r]); $rules['station_id'][$r] = ['required', 'int', Rule::notIn($rStationIds)]; $rStationIds[$r] = $temp; }
Looking for an element in an array in 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
Understanding how PHP treats references to arrays
In PHP 5.5.33, I want to create an array of arrays, inside a repeat loop. I have found 3 different ways of doing this, which give 3 different results. The first result is the one I want, so I have a solution. What I need is an understanding of why these three ways lead to different outcomes. The first two examples make sense to me. The third seems to apply alien logic. In the third example, I create a new reference to a new array on each iteration, and yet the same reference is added to the output array each time. Why does $inner, in the last example, not get recreated at a new memory address each time? <?php // Inner array added after it is changed $outer = array(); for ($ii=0; $ii<3; $ii++) { $inner = array("value" => 0); $inner["value"] = $ii; $outer[$ii] = $inner; } echo json_encode($outer); // [{"value":0},{"value":1},{"value":2}] ?> <br /> <?php // Innner array added as a copy, and then changed $outer = array(); for ($ii=0; $ii<3; $ii++) { $inner = array("value" => 0); $outer[$ii] = $inner; $inner["value"] = $ii; } echo json_encode($outer); // [{"value":0},{"value":0},{"value":0}] ?> <br /> <?php // Inner array created, then added by reference, then changed $outer = array(); for ($ii=0; $ii<3; $ii++) { $inner = array("value" => 0); // shouldn't this be different each time? $outer[$ii] = &$inner; $inner["value"] = $ii; } echo json_encode($outer); // [{"value":2},{"value":2},{"value":2}] ?>
It is simple - on the 3th sample you're creating the array of 3 synonyms to the variable $inner['value']. In same tame you every time change the $inner['value'] to $ii. On the end you have array of 3 pointers, which point to $inner['value'], but $inner['value'] obtained 2 - that is and the result. And in case you are expecting that $inner = array("value" => 0); will take different place - you aren't on right way. This is equal if you empty and create the array - it is reseting the array every time.
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 ; }
Unable to change session variables in zend .. is the approach wrong?
Here are the steps that i have followed till now : Firstly i have initialized the namespace for my session $guest_events = new Zend_Session_Namespace('guest_events'); then added an array to the session $guest_events-> events = array(); then i added some events to the array. which looks like : Array ( [amount_0] => 1 [event_id_0] => 69 [event_title_0] => Sunday Collection [amount_1] => 11 [event_id_1] => 78 [event_title_1] => Test event ) Now in my another controller when i try to implement edit amount functionality through ajax : $event_id = $this-> getRequest()-> getParam('event_id'); $edit_amount = $this-> getRequest()-> getParam('edit_amount'); $event_title = $this-> getRequest() -> getParam('event_title'); $guest_events = new Zend_Session_Namespace('guest_events'); $event_array = $guest_events-> events; for ($i = 0; $i < 5; $i ++) { if (array_key_exists('event_id_'.$i, $event_array)) { if ($event_array['event_id_'.$i]==$event_id && $event_array['event_title_'.$i]==$event_title) { // unset the amount and replace with new one unset($guest_events-> events-> amount_0); $guest_events-> events-> amount_0 = $edit_amount; } } } i have tried everything but the session variables remain unchanged .. can anyone tell why ?? :(
If the element events is an array in your Zend_Session_Namespace object, then you should be setting it like this: $guest_events-> events['amount_0'] = $edit_amount; instead of like: $guest_events-> events-> amount_0 = $edit_amount; Also, since you are in a loop which finds the correct numeric value, I think it should actually be: $guest_events-> events['amount_' . $i] = $edit_amount;
I figured out the problem .. it isn't going inside the inner if loop .. i.e : if ($event_array['event_id_'.$i]==$event_id && $event_array['event_title_'.$i]==$event_title) { // unset the amount and replace with new one unset($guest_events-> events-> amount_0); $guest_events-> events-> amount_0 = $edit_amount; } still cant figure out why this is happening though :/