Use a parameter as an index in PHP - php

I am trying to do a thing that I dont know if can work. Also accept other ideas.
I have an array passed as a parameter where the index is the task id in the database and the value is the last syncronization for the task with the database
$sync=Array
(
[22805] => 1406822699
[22806] => 1406824500
[22807] => 1406838670
)
Then I do a select in the database which gives me the whole of tasks and I one to update on the database only some tasks, basically the ones that are out of date.
//$tasks is the list of all tasks from the database and $sync is the array which is pased by the user
foreach($tasks as $task)
{
if($task['sync']<=$sync[$task['taskList_id']])
{}
else
{//to be updated
$taskModel->updateLastSync($task['taskList_id'],$time);
$task['sync']=$time;
}
}
This is the problematic line and what I need to know how to do.
$sync[$task['taskList_id']]
I want to use a parameter as index to get the value of an array.
How can I achieve this.
Because this other idea is another foreach for $sync inside the foreach for $tasks

Without seeing the full script or having access to var_dump at certain locations it's hard to say what's going on but here are some things to check:
Make sure you're getting results from the database query and that they are assigned to the $tasks variable
Make sure your $sync array values and $task['sync'] are integer types and not strings or the '<=' comparison may have unexpected results
I don't know where $time gets its value from based on code I see so verify that it does actually have a value when you try to set it
A good first step when debugging is to try to isolate the problem's location first and then worry about the cause. Using something like var_dump to verify that values of certain variables are as expected at various locations in your script is very useful. Once you know where things start going wrong you can focus your attention in the right place to find out why and come up with a solution. I recommend doing this and letting us know what you find.

I solved my question.
Which was if this is allowed, I tested and it is.
$ar=array('1'=>'a','2'=>'b','3'=>'c');
$index=2;
echo $ar[$index];

Related

I need to add fields to a JSON string in PHP, but I'm having problems

So... I need to save a large-ish amount of data from a platform with an excruciatingly limited amount of memory.
Because of this, I'm basically storing the data on my webserver, using a php script to just write JSON to a flat file, because I'm lazy af.
I could go to the trouble of having it store the data in my mysql server, but frankly the flat file thing should have been trivial, but I've run up against a problem. There are several quick and dirty workarounds that would fix it, but I've been trying to fix it the "right" way (I know, I know, the right way would be to just store the data in mysql, but I actually need to be able to take the json file this produces and send it back to the platform that needs the data (In a ridiculously roundabout fashion), so it made sense to just have the php save it as a flat file in the first place. And It's already working, aside from this one issue, so I hate to reimpliment.
See... Because of the low memory on the platform I'm sending the json to my server from... I'm sending things one field at a time. Each call to the php script is only setting ONE field.
So basically what I'm doing is loading the file from disk if it exists, and running it through json_decode to get my storage object, and then the php file gets a key argument and a value argument, and if the key is something like "object1,object2", it explodes that, gets the length of the resulting array, and then stores the value in $data->$key[0]->$key[1].
Then it's saved back to disk with fwrite($file, json_encode($data));
This is all working perfectly. Except when $value is a simple string. If it's an array, it works perfectly. If it's a number, it works fine. If it's a string, I get null from json_decode. I have tried every way I can think of to force quotes on to the ends of the $value variable in the hopes of getting json_decode to recognize it. Nothing works.
I've tried setting $data->$key[0]->$key[1] = $value in cases where value is a string, and not an array or number. No dice, php just complains that I'm trying to set an object that doesn't exist. It's fine if I'm using the output of json_decode to set the field, but it simply will not accept a string on its own.
So I have no idea.
Does anyone know how I can either get json_decode to not choke on a string that's just a string, or add a new field to an existing php object without using the output of json_decode?
I'm sure there's something obvious I'm missing. It should be clear I'm no php guru. I've never really used arrays and objects in php, so their vagaries are not something I'm familiar with.
Solutions I'm already aware of, but would prefer to avoid, are: I could have the platform that's sending the post requests wrap single, non-numeric values with square braces, creating a single item array, but this shouldn't be necessary, as far as I'm aware, so doing this bothers me (And ends up costing me something like half a kilobyte of storage that shouldn't need to be used).
I could also change some of my json from objects to arrays in order to get php to let me add items more readily, but it seems like there should be a solution that doesn't require that, so I'd really prefer not to...
I skim through your post.
And I know this works for StdClass :
$yourClass->newField = $string;
Is this what you wanted ?
OK so... ultimately, as succinctly as possible, the problem was this:
Assuming we have this JSON in $data:
{
"key1":
{
"key2":["somedata","someotherdata"]
}
}
And we want it to be:
{
"key1":
{
"key2":["somedata","someotherdata"],
"key3":"key3data"
}
}
The php script has received "key=key1,key3&value=key3data" as its post data, and is initialized thusly:
$key = $_POST["key"];
$key = explode($key,",");
$value = $_POST["value"];
...which provides us with an array ($key) representing the nested json key we want to set as a field, and a variable ($value) holding the value we want to set it to.
Approach #1:
$data->$key[0]->$key[1] = json_decode($value);
...fails. It creates this JSON when we re-encode $data:
{
"key1":
{
"key2":["somedata","someotherdata"],
"key3":null
}
}
Approach #2:
$data->$key[0]->$key[1] = $value;
...also fails. It fails to insert the field into $data at all.
But then I realized... the problem with #2 is that it won't let me set the nonexistent field, and the problem with approach #1 is that it sets the field wrong.
So all I have to do is brute force it thusly:
$data->$key[0]->$key[1] = json_decode($value);
if (json_decode($value) == NULL)
{
$data->$key[0]->$key[1] = $value;
}
This works! Since Approach #1 has created the field (Albeit with the incorrect value), PHP now allows me to set the value of that field without complaint.
It's a very brute force sort of means of fixing the problem, and I'm sure there are better ones, if I understood PHP objects better. But this works, so at least I have my code working.

Wordpress - Passing variable to function - how to correctly pass list of numbers

I am trying to restrict content within a Wordpress template file and am using a plugin called Paid Memberships Pro to do so.
The code below restricts content to members with 'levels' of 1 or 2.
if(pmPro_hasMembershipLevel(array(1,2))){
restricted content goes here
}
The problem comes when I try to use a variable to provide the levels. These levels are held in a custom field group 'restrictions' with field name 'pmpro_id'. I access these levels within the template using...
foreach($restrictions as $restriction){
$temp=get_field('pmpro_id', $restriction->ID );
$temp_array[]=$temp;
}
$levels=implode(',', $temp_array);
If I then pass $levels to pmPro_hasMembershipLevel, this works fine if there is only one level but fails if there are 2 or more. I believe this is because the variable type is then a string rather than integer? I had previously tried to pass the $temp_array directly though I felt this wouldn't work and was correct.
I realise this is probably PHP 101. I have searched but don't really know what I'm looking for to be honest! I am not a developer and this is the last thing holding me back from finishing this project so ANY help anyone could provide would be brilliant. Thanks in advance.
You don't need to implode $temp_array if pmPro_hasMembershipLevel accepts array as its argument. When you implode an array you get string as a return value — that's not what you want here. If you think that the issue might be with the type of values, then you can try to cast them to integers, like this $temp_array[]= (int) $temp;

conditional in_array trouble with PHP mySQL

I have firePHP so i know exactly what the variables are, but I can't figure out why this code doesn't change it.
I receive from a mySQL call $query (which if returned produces [{"type":"2"}])
I have 4 potential types, and things can be multiple types (i.e. [{"type":"1"},{"type":"2"}])
Now I want to read this data and run various other functions based on the type it has, that is: if it's only type 2, call function TWO, if it's type 1 and 2 call function ONE and function TWO. I thought this would be easiest if i moved all the data into another array.
Here is the code I currently have:
$result = array('message'=>false, 'money'=>false, 'glasses'=>false, 'exclamation'=>false);
if (in_array('1',$query)) {$result['message'] = true;}
if (in_array('2',$query)) {$result['money'] = true;}
if (in_array('3',$query)) {$result['glasses']=true;}
if (in_array('4',$query)) {$result['exclamation']=true;}
echo json_encode($result);
This however does not update the $result array (as I can tell all of the values of $message are false in firePHP.... Thus I assume something is wrong with my if statements, but what?
I´m not sure about the value of $query, but if it is something like:
array [0 => '{"type":"2"}']
You would have to use:
in_array('{"type":"2"}',$query)
as that is the value of your variable.
Is it because the results returned in $query are arrays of arrays, and thus in_array is only searching at the top level and not sub-levels? It seems like what you want is to recursively search $query.

CakePHP find returns same value every time

Hey guys, been having this problem for a while now, and can't for the life of me seem to track down anything remotely helpful.
I'm trying to, once a user logs into the application (using the built-in Auth component), use the school_id field to find the name of the school that they are associated with (and display this name in the header of the view). I also figure that I will need to call up various other pieces of school information in other actions down the road.
I've tried both of the following, but neither seems to work. No matter whether I School->find() based on the user's "school_id" or by a number that I have included manually. It simply returns the information of the same school every time (the school with the ID of 1).
Here's what I've tried:
$this->set('school_name', $this->School->find('first', array('conditions' => array('School.id' == 2))));
$this->set('school_info', $this->School->find('first', array('conditions' => array('School.id' == $this->Auth->User('school_id')))));
$this->set('school_info', $this->School->find($this->Auth->User('school_id');
Once again, not a problem with the code not returning anything. It just returns the same school every time (where ID = 1).
As you can imagine, this has been fairly frustrating, and I would love any help that you could provide.
Thanks,
Ben
You are using the == sign instead of => in your condition.
It should be:
$this->School->find('first', array('conditions' => array('School.id' => 2))));
Remember: == is a conditional operator. => is the arrow notation used to create array key-value pairs.
A short way to do it would be:
$this->School->findById($this->Auth->user('school_id'));
If you're supplying the id, supply it to the findById and not the all-encompassing find method. That said, you should still take care to see that you're using the right operators. :)
Quick Note: 'School.id' == 2 evaluates to false and array(false) is an array with one element false which is why you didn't get any errors.

PHP Change Array Over and Over

I have any array
$num_list = array(42=>'0',44=>'0',46=>'0',48=>'0',50=>'0',52=>'0',54=>'0',56=>'0',58=>'0',60=>'0');
and I want to change specific values as I go through a loop
while(list($pq, $oin) = mysql_fetch_row($result2)) {
$num_list[$oin] = $pq;
}
So I want to change like 58 to 403 rather then 0.
However I always end up getting just the last change and non of the earlier ones. So it always ends up being something like
0,0,0,0,0,0,0,0,0,403
rather then
14,19,0,24,603,249,0,0,0,403
How can I do this so it doesn't overwrite it?
Thanks
Well, you explicititly coded that each entry should be replaced with the values from the database (even with "0").
You could replace the values on non-zero-values only:
while(list($pq, $oin) = mysql_fetch_row($result2)) {
if ($pq !== "0") $num_list[$oin] = $pq;
}
I don't get you more clear, i thought your asking this only. Check this
while(list($pq, $oin) = mysql_fetch_row($result2)) {
if($oin==58) {
$num_list[$oin] = $pq;
}
}
In my simulated tests (although You are very scarce with information), Your code works well and produces the result that You want. Check the second query parameter, that You put into array - namely $pg, thats what You should get there 0,0,0,0,0...403 OR Other thing might be that Your $oin numbers are not present in $num_list keys.
I tested Your code with mysqli driver though, but resource extraction fetch_row is the same.
Bear in mind one more thing - if Your query record number is bigger than $numlist array, and $oin numbers are not unique, Your $numlist may be easily overwritten by the folowing data, also $numlist may get a lot more additional unwanted elements.
Always try to provide the wider context of Your problem, there could be many ways to solve that and help would arrive sooner.

Categories