I have a multidimensional session array that is set. Session start is called at the top of the file and all the fields are set as the examples
//set variables
$locked="unlocked";$name="BMX";$sport_activity="sport";$quantity="1";$price="600";
//set variables to array
$sports_array = array(0 => array(
'i_locked' => $locked,
'i_name' => $name,
'i_quantity' => $quantity,
'i_price' => $price,
'i_sport_activity' => $sport_activity,
'i_base_price' => $price));
//set multidimensional session array
$_SESSION["activity"][] = $sports_array;
Then the array is called in a PHP loop.
$arrayID = -1;
//foreach loop
foreach($_SESSION['activity'] as $key){
foreach($key as $list){
$arrayID += 1;
?>
//echo all the array items individually in separate divs
<form>
<div>
<?php echo $list['i_locked']?>
</div>
// ..... etc
<input type="hidden" name="ArrayNum" value="<?=$arrayID?>">
<input type='submit' name='Confirm_button'>
</form>
All of this works, what i would like to then do is change a variable and add new ones.
I have come across array_push() for adding new fields onto an array. And i have tried the following below, but either it adds an entire array stack or delete's the array stack.
if(isset($_POST["Confirm_button"])){
$time = 'pm';
$date = 'feb';
$_SESSION['activity'][$_POST['ArrayNum']]['i_locked'] = 'locked';
array_push($_SESSION['activity'][$_POST['ArrayNum']],'i_time'=>$time,'i_date'=>$date);
}
Any help or a point in the right direction for best practices would be most appreciated
************************* Re- Edit ****************************************
Credit to #Suchit Kumar
Was able to get the problem fixed based on his help.
The first issue of changing an element of the array works with the following code. And correctly finds the element that needs changing.
$_SESSION['activity'][$_POST['ArrayNum']][0]['i_locked'] = 'locked';
The second issue of adding new elements to the array works with the following code.
$time = 'pm';
$date = 'feb';
$_SESSION['activity'][$_POST['ArrayNum']][0]['i_time'] = $time;
$_SESSION['activity'][$_POST['ArrayNum']][0]['i_time'] = $date;
I think you can not use key value pair in array_push without using array('key'=>'value') format. in this case you have to do something like this dynamically:
and the way you are creating $_SESSION["activity"][]=$sports_array;.your array will come on index ['activity'][0][0].
IT is an Example to point out the problem But you need to follow this Dynamically by creating dynamic indexes.
<?php
$time = 'pm';
$date = 'feb';
$_SESSION['activity'][0][0]['i_time']=$time;// when already some elements are there with the key
$_SESSION['activity'][0][0]['i_date']=$date;
echo "<pre>";
print_r($_SESSION);
echo "<pre>";
if you want to add another array do $_SESSION['activity']:
$time1 = 'am';
$date1 = 'mar';
array_push($_SESSION['activity'][$_POST['ArrayNum']],array('i_new'=>$time1,'i_new1'=>$date1));//createing new key and pussing the array.
to update any value in an array do this:
check if:
if(isset($_SESSION['activity'][0][1]['i_time'])){// you can use foreach to access eack key value pair before if condition
$_SESSION['activity'][0][1]['i_time']=$newtime;
}
?>
NOTE: this is only to show your how you will do in your original code.
Related
I have an array that is called within a wordpress loop. I also need to call the same array on the same page outside of the loop.
The second array always returns blank, and that happens even if I use copy the array and add it outside of the loop where I'm using it a second time.
I have no idea why this is happening and how to proceed.
<?php
// get ACF custom relationship field 'select'
$rmcwordwide = get_field('rights_management_control_by_worldwide', $post->ID); $rmcwordwidearray = str_split($rmcwordwide,2);
$rmcnorthamerica = get_field('rights_management_control_by_northamerica', $post->ID); $rmcnorthamericaarray = str_split($rmcnorthamerica,2);
$rmcusaonly = get_field('rights_management_control_by_usaonly', $post->ID); $rmcusaonlyarray = str_split($rmcusaonly,2);
$rmcusalatam = get_field('rights_management_control_by_usalatam', $post->ID); $rmcusalatamarray = str_split($rmcusalatam,2);
$rmclatamonly = get_field('rights_management_control_by_latamonly', $post->ID); $rmclatamonlyarray = str_split($rmclatamonly,2);
// Merger arrays
$rmcarray = array_merge( (array)$rmcwordwidearray, (array)$rmcnorthamericaarray, (array)$rmcusaonlyarray, (array)$rmcusalatamarray, (array)$rmclatamonlyarray );
// GET USERS COUNTRY LOCATION FROM IP USING MAXMIND
require '/home/xxxx.com/public_html/vendor/autoload.php';
$gi = geoip_open("/home/xxxx.com/public_html/GeoIP.dat",GEOIP_STANDARD);
$ip = strtolower($_SERVER['REMOTE_ADDR']);
$countrycode = strtolower(geoip_country_code_by_addr($gi, $ip));
geoip_close($gi);
if (in_array($countrycode, $rmcarray)): ?>HELLO<?php endif; ?>
So there's one string in each of the arrays. I then break down the string and make a new array for each.
Then I merge the arrays.
Then I get the users location and if an entry in the merged array and the users country code match then...
Create your own array var before the loop starts. Inside of the loop, add the loop result to the new array each iteration. Then use the newly populated array anywhere you want outside of the loop.
I'm a beginner in PHP. I have a text file like this:
Name-Id-Number
Abid-01-80
Sakib-02-76
I can take the data as an array but unable to take it as an associative array. I want to do the following things:
Take the data as an associative array in PHP.
Search Number using ID.
Find out the total of Numbers
I believe I understand what you want, and it's fairly simple. First you need to read the file into a php array. That can be done with something like this:
$filedata = file($filename, FILE_IGNORE_NEW_LINES);
Now build your desired array using a foreach() loop, explode and standard array assignment. Your search requirement is unclear, but in this example, I make the associated array element into an array that is also an associative array with keys for 'id' and 'num'.
As you create the new array, you can compute your sum, as demonstrated.
<?php
$filedata = array('Abid-01-80', 'Sakib-02-76');
$lineArray = array();
$numTotal = 0;
foreach ($filedata as $line) {
$values = explode('-', $line);
$numTotal += $values[2];
$lineArray[$values[0]] = array('id' => $values[1], 'num' => $values[2]);
}
echo "Total: $numTotal\n\n";
var_dump($lineArray);
You can see this code demonstrated here
Updated response:
Keep in mind that notices are not errors. They are notifiying you that your code could be cleaner, but are typically suppressed in production.
The undefined variable notices are coming because you are using:
$var += $var without having initialized $var previously. Note that you were inconsistent in this practice. For example you initialized $numTotal, so you didn't get a notice when you used the same approach to increment it.
Simply add just below $numTotal = 0:
$count = 0;
$countEighty = 0;
Your other notices are occurring most likely due to a blank line or string in your input that does not follow the pattern expected. When explode is executed it is not returning an array with 3 elements, so when you try and reference $values = explode('-', $line); you need to make sure that $line is not an empty string before you process it. You could also add a sanity check like:
enter code hereif (count($values) === 3) { // It's ok to process
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.
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 ;
}
I have always sucked at complex arrays there must be something in my brain preventing me from ever understanding them. I will try to make this example really simple so we will not go off topic. I use this code to use numbers to represent each file name:
$mod_nums = array('1' => $input_zip_path . '01_mod_1.0.2.zip',
'2' => $input_zip_path . '02_mod_1.0.1.zip',
);
So when I use $mod_nums['01'] it will display the path to that file. I have an array from the script that put these $mod_nums values into an array like so:
$files_to_zip = array(
$mod_nums['1'],
$mod_nums['2']
);
That worked fine. Now I wanted to add a $_POST value so that I can enter numbers like 1,2 and other numbers that I add to the $mod_nums array later like 1,3,6,12 for example. So I used an explode for those posted values:
$explode_mods = explode(",", trim($_POST['mods']));
Now for the big question that is racking my brain and spent hours on and cannot get it to work.... I need for $files_to_zip to still be in an array and display the posted values of $mod_nums. So it would be like:
$files_to_zip = array( HAVE $_POSTED VALUES IN HERE );
I hope that makes sense. I need $files_to_zip to remain in array format, grab the file path to the zip files from the $mod_nums array, and display it all correctly so it would dynamically output:
$files_to_zip = array('01_mod_1.0.2.zip', '02_mod_1.0.1.zip');
so posted numbers will appear in an array format for the $files_to_zip variable. Make sense? In short I need an array to have dynamic values. Thanks :)
EDIT
Phew I figured it out myself from memory when I worked on something similar many years ago. This looks tough but it isn't. I had to use a foreach and assign the variable into an array like so:
$blah = array();
foreach ($explode_mods as $value)
{
$blah[] = $mod_nums[$value];
}
then I just assigned $files_to_zip to $blah:
$files_to_zip = $blah;
works perfectly :) I just forgot how to dynamically assign values into an array.
// filenames array
$mod_nums = array('1' => $input_zip_path . '01_mod_1.0.2.zip',
'2' => $input_zip_path . '02_mod_1.0.1.zip',
);
// mod_num keys
$explode_mods = explode(',', trim($_POST['mods']));
// array to hold filenames
$files_to_zip = array();
// loop over all the mod_num keys submitted via POST
foreach($explode_mods as $key){
// save the filename to the corresponding array
$files_to_zip[] = $mod_nums[$key];
}
maybe i havn't understood you right, but won't this just be a simple foreach-loop to add the entrys to $files_to_zip like this:
$explode_mods = explode(",", trim($_POST['mods']));
foreach($explode_mods as $k){
$files_to_zip[] = $mod_nums[$k];
}