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.
Related
I've seen a few questions and the ones worth referencing
How can i delete object from json file with PHP based on ID
How do you remove an array element in a foreach loop?
How to delete object from array inside foreach loop?
Unset not working in multiple foreach statements (PHP)
The last two from the list are closer to what I'm intending to do.
I've got a variable names $rooms which is storing data that comes from a particular API using Guzzle
$rooms = Http::post(...);
If I do
$rooms = json_decode($rooms);
this is what I get
If I do
$rooms = json_decode($rooms, true);
this is what I get
Now sometimes the group exists in the same level as objectId, visibleOn, ... and it can assume different values
So, what I intend to do is delete from $rooms when
group isn't set (so that specific value, for example, would have to be deleted)
group doesn't have the value bananas.
Inspired in the last two questions from the initial list
foreach($rooms as $k1 => $room_list) {
foreach($room_list as $k2 => $room){
if(isset($room['group'])){
if($room['group'] != "bananas"){
unset($rooms[$k1][$k2]);
}
} else {
unset($rooms[$k1][$k2]);
}
}
}
Note that $room['group'] needs to be changed to $room->group depending on if we're passing true in the json_decode() or not.
This is the ouput I get if I dd($rooms); after that previous block of code
Instead, I'd like to have the same result that I've shown previously in $rooms = json_decode($rooms);, except that instead of having the 100 records it'd give only the ones that match the two desired conditions.
If I am not totally wrong, then this should do the trick for you:
$rooms = json_decode($rooms);
$rooms->results = array_values(array_filter($rooms->results, function($room) {
return property_exists($room, 'group') && $room->group != "banana";
}));
Here is a verbose and commented version of this one above:
$rooms = json_decode($rooms);
// first lets filter our set of data
$filteredRooms = array_filter($rooms->results, function($room) {
// add your criteria for a valid room entry
return
property_exists($room, 'group') // the property group exists
&& $room->group == "banana"; // and its 'banana'
});
// If you want to keep the index of the entry just remove the next line
$filteredRooms = array_values($filteredRooms);
// overwrite the original results with the filtered set
$rooms->results = $filteredRooms;
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.
I need to apply some functions to a key items inside an array before moving on with the whole array, but I probably miss something.
Here is my code:
// Get generated datas
$data_post = $this->input->post('form_data'); // Need to update this array
foreach( $data_post as $data ){
$data['password'] = password_encrypt($data['password']);
var_dump($data); // Password encryption succeed
}
var_dump($data_post); // But here, the password is still the same, no encryption applied
So as commented in the CODE section, how should I update the main $data_post array with the modifications made in foreach() ?
Inside a foreach, data isn't passed by reference. This means that modifying the variable $data doesn't modify $data_post. You can modify the original array in more than one way, but here is how I would do it:
foreach( $data_post as $key => $data ){
$data_post[$key]['password'] = password_encrypt($data['password']);
}
Note that this presumes that $data_post contains multiple sub arrays, each with the password key (or else notices will be thrown).
Try this:
$data_post = $this->input->post('form_data'); // Need to update this array
foreach( $data_post as $k=>$v ){
if($k == "password"){
$data_post[$k] = password_encrypt($v);
}
}
var_dump($data_post);
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 need to truncate string and rewrite it back to array
I have got a function where I get data from data base
$data['about_text_list'] = $this->about_text_model->get_array();
I get these fields from data base : id, num, header, text, language
I need to strip_tags and truncate text with function word_limiter
foreach ($data['about_text_list'] as $items)
{
$data['about_text_list']['text'] = word_limiter($items['text'], 100);
$data['about_text_list']['text'] = strip_tags($items['text']);
}
in view I do foreach
<? foreach ($about_text_list as $line) : ?>
<td><?=$line['text']?></td>
<? endforeach; ?>
But I get error, please tell me how to do correct things like this...
In the loop in your controller, you're limiting the word count, then setting that to the value in the array. Then, you're overwriting that value with the strip_tags function. You're using both functions on the same value instead of using the altered values. (And I would strip the tags first, then limit the word count.)
You're also just overwriting the $data['about_text_list']['text'] value each iteration. I'm assuming this needs to be an array of 'text' values? I would create a new array with the updated content and merge your $data['about_text_list'] array with the new array.
Change that loop to this:
$newarray = array();
foreach ($data['about_text_list'] as $key => $value)
{
$item_text = $value['text'];
$altered = strip_tags($item_text);
$newarray[$key]['text'] = word_limiter($altered, 100);
}
$data['about_text_list'] = array_merge($data['about_text_list'], $newarray);
// here, you create a new empty array,
// then loop through the array getting key and value of each item
// then cache the 'text' value in a variable
// then strip the tags from the text key in that item
// then create a new array that mirrors the original array and set
// that to the limited word count
// then, after the loop is finished, merge the original and altered arrays
// the altered array values will override the original values
Also, I'm not sure what your error is (as you haven't told us), but make sure you're loading the text helper to give you access to the word_limiter function:
$this->load->helper('text');
Of course, this all depends on the structure of your array, which I'm guessing at right now.