Trying to access an associative array item via timestamp - php

So I have a MySQL object, which has columns (keys) for timestamp, category, and value.
Timestamp is a UNIX timestamp. Category is an emotion word. Value is a numeric value.
Here's my code:
foreach ($twitromney['timestamp']) {
echo $twitromney['timestamp']['value'];
}
Now, this should display the value per timestamp, right? This is how ONE of the arrays looks (the object has hundreds of these):
Array ( [category] => composed [value] => 330 [timestamp] => 1344384476.94 )
What I am trying to do is get the value per category per timestamp. Except for value, which is variable, both timestamp and category should repeat. I.e., there should be multiple 1344384476.94s, as well as several composed category values.
Once I get that (I don't think I need help with this), I am going to add the values for a particular category for a particular day (by converting the timestamp) together and output this.

Try this:
foreach ($twitromney as $flip) {
echo "$flip['category'], $flip['timestamp'], $flip['value'] <br />";
}

I really didn't understand your question but you have supplied wrong arguments in your foreach, you can try this
foreach ($twitromney as $item) {
echo $item['timestamp'].'<br />';
}
to echo every timestamp instead of
foreach ($twitromney['timestamp']){
echo $twitromney['timestamp']['value'];
}
If you see this example then you'll get an idea.

Related

Loop Columns in Recordset

Please understand this is not how I would have designed this, nor is it the proper way to do something like this.
However, since I was given this task, and have absolutely no way around the way the data is structured, I am tasked with working with what I was given.
I have a table structured as such:
ID
UniqueName
DisplayName
Tag1
Tag...
Tag27
Yes, I have 27 columns, Tag1 - Tag27
NOTE: This cannot be changed due to the data coming from 15 year old software that is not updated, nor is there any chance of it being updated. (Hence my dilema)
I am getting my resultset utilizing PDO's fetchAll(PDO::FETCH_ASSOC)
How can I loop over these Tag* columns, and just the Tag* columns, without having to type out rs[$i]['Tag#'] for each individual one, also noting that there may be instances where I could have 14 Tag columns` instead of the 27 I state in this example...
COLUMN CODE:
// prod_opts_value_fields_prefix = "Tag"
foreach ($rs[$i] as $key => $val) {
if ( strpos ( strtolower ( $key ), strtolower ( $prod_opts_value_fields_prefix ) ) !== false ) {
$vals .= $val . '|';
echo $val . '<br />';
}
}
Nothing is getting echo'd
You could run a foreach over the rs[$i] and check if the key contains 'Tag' with strpos and go from there.
Alternatively you could use just a for loop running on 1 to 27 (or any maximum Tag value) and have an if condition checking if rs[$i]['Tag$N'] (where N is the for loop counting variable) isset, if not break from the loop as that means you've gone through all possible Tags.
The second solution here does have the assumption Tags are always numbered sequentially and in ascending order.
If you need it in multiple places, I'd probably add a setting to a preferences array or a constant that you can easily re-use:
const TAG_COLUMNS = [
'Tag1',
...
'Tag27',
];
You can use that wherever you need it to loop over a result set.

Simple variable assignment from two-dimensional array in php

I have a two-dimensional array with two key values, [program] and [balance], created by a MySQL SELECT statement in WordPress. I know what the values of [program] will be (they never change) - it's the balances I'm interested in.
For example:
*[program] = 'Sales', [balance] = 10,000*
*[program] = 'Commission', [balance] = 1,250*
All I want to do is assign the balance value to a variable, so I will have:
*$sales = (the balance for the Sales program)*
*$commission = (the balance for the Commission program)*
I know I'm being thick here, but I cannot see how to do this after about an hour of searching and screwing around with php. It's a total brain block and all the references I can find online talk about loops and echoing all the values and stuff.
Would appreciate a de-blocking!
//make a function
function findBalanceByProgram($inputArray,$program)
//loop trough all the keys on the first dimension
foreach($inputArray as $val){
//check in the second dimension if your program is the same as the program you are checking for
if($val['program']==$program)
//if so.. return the value and jump out of the function
return $val['balance'];
}
}
//an example of use.
echo findBalanceByProgram($yourArray,'sales');

Editing the object returned by $wpdb->get_results(SQL)

We have a nasty database call using the Wordpress function $wpdb->get_results(SQL).
After receiving the result in PHP, we need to make a few changes to the result.
So can anyone tell me how I can:
1) Remove specific rows from the get_results() returned object.
2) Change the values of the specific columns in specific rows in the returned object.
I.e. if the object returned is $nastyData, we need to:
1) Remove specific rows from $nastyData
2) Change the value of specific columns in specific rows in $nastyData, for example $nastyData->name for a specific row.
Any ideas?
I have thought about makeing get_results() return the data as an array, but that will create problems in other places in our code (where the code expects to receive an object).
Thanks,
Mads
To start with, your "Nasty database call" should be optimized to be less nasty. More specifically, only query the results you want so that you don't have to remove stuff afterwords. This is the best solution.
If you insist on trying to modify the objects, this is a workaround. According to the documentation, when returning objects, they are returned in one of two ways:
OBJECT - result will be output as a numerically indexed array of row objects.
OBJECT_K - result will be output as an associative array of row objects, using first column's values as keys (duplicates will be discarded).
So, knowing that the result is an array of objects, we can get to each individual instance using a foreach construct:
$results = $wpdb->get_results( $nastySQL );
foreach($results as $index => $result)
{
// Change name column to FirstName using copy and delete
$tmp = $result->name;
unset($result->name);
$result->FirstName = $tmp;
// Remove specific row
if( $result->name == "Tom")
{
unset($results[$index]);
}
}
Below code will replace the value coming from specific field of database table, if name field has value like Reo and you want to replace it with other name like John then you can to do this via below code
$results = $wpdb->get_results( $nastySQL );
foreach($results as $key => $value){
$results[$key]->name= 'John';
}
return $results;

Object Loop Not Working as Expected

I will be honest, I have just started learning objects and I am stuck.
I want to loop through an array of objects and display the name and description for each. But either nothing is displayed or it displays all the names first and then all the descriptions.
I am pulling the information from an API into the object:
// get tasks
foreach($tasksList->items as $task_details) {
$tasks_name[$task_details->id]=$task_details->name;
$tasks_desc[$task_details->id]=$task_details->description;
$tasks_details[$task_details->id]=$task_details->id;
$tasks_progress[$task_details->id]=$task_details->progress;
}
foreach($tasks_name as $taskid=>$my_task_name) {
echo "Task_Name: " . $my_task_name . "</br>";
$task_id = $task_details->id;
foreach($tasks_desc as $taskid1=>$my_task_desc) {
if($taskid==$task_details->id) {
echo "Task_Desc: " . $my_task_desc . "</br>";
}
}
}
Now what I don't understand is: inside the first foreach loop it is like a while loop while i=0, it checks $tasks_name[0], then $tasks_name[1] and so on.
However, I am not sure how to figure out what the id is in the current loop it is on, so I can tell it to only print the description of the current loop and not display all of them.
To be honest I am copying this from another example, but I don't quite understand it. I plan to study objects more, but this is holding me up on my current code:
foreach($tasks_desc as $taskid1=>$my_task_desc)
I understand it is looping through all the $tasks_desc and assigning the value to $my_task_desc but what is the signifigance of $taskid?
Sorry for the newbie questions. :)
This is poorly written. I would move on to another tutorial if it's a tutorial. Either that or the line that task_id is used was left out.
Anyway, tasks_name is an array of tasks indexed by the ID. So the outer loop in the second block loops over the keys/values of that array (the ID is the key, taskid. It was assigned by $task_details->id in the first loop above).
The second loop goes over all of the tasks again, but this time by description task_desc instead of by name. It's trying to find the task_desc with an ID that matches the ID of the task_name before (which would make it the same task).
That's unnecessary, though, because you could just store all of the entries (name, desc, etc.) in one array indexed by the ID instead of storing each in their own array:
(this is the first loop):
foreach($tasksList->items as $task_details) {
$all_tasks[$task_details->id]['name'] = $task_details->name;
$all_tasks[$task_details->id]['desc'] =$task_details->description;
// Don't need the ID again; it's the key
$all_tasks[$task_details->id]['progress'] = $task_details->progress;
}
However, you don't even need to do that, because you can just iterate over tasksList->items when you need to.
There's no need for two loops. To display name and description for each object, one loop is enough:
foreach($tasksList->items as $task_details) {
echo 'name: ', htmlspecialchars($task_details->name);
echo ', description: ', htmlspeciachars($task_details->description);
}
(I also don't understand why you want to store every object field in its own array first?)

PHP and MySQL Data Formatting

I've created a database and stored some data along with the scheduled date for each item. I would like to output a schedule in the format like this:
January 1:
- 1:00 pm
Doctors
Appt -
4:45 pm
Birthday
Party January 3:
- 10:00 am
Hair Cut
Appt -
4:50 pm
Bob's House
The problem I've run into is I'm not sure on how to output the data like this. I only want to display the date once but the time and date are in the same row, so a foreach loop won't work. If there's a better way to structure my data to achieve this then I'm willing to do that also.
My Table contains the following data for each row:
id, name, about, date, time
Any help would be much appreciated. Thanks
You don't need to structure your data differently, it sounds like it's been normalised properly. Instead pre-process your data into a temporary array that groups results by date, then loop over that:
$dateArray = array();
foreach($dbResult as $result) {
$dateArray[$result['date']][] = $result;
}
foreach($dateArray as $date => $entries) {
echo $date . ':<br>';
foreach($entries as $entry) {
echo $entry['time'] . '<br>' . $entry['name'];
}
}
Avoid doing two queries because you can do what you need with one and it'll put your database under less load.
Personally I would consider structuring the database as such:
Table: Dates(DateId, Date)
Table: Times(TimeDateID, DateID, Time)
Table: Appointment(AppointmentID, Name)
Table: Appointment_Time(AppointmentID, TimeDateID)
That way you could loop through all your dates, for each date loop through all the times that have that DateID, then loop through all your appointment_times with that timedateID
Pull the data and then create a multidimensional array from it, e.g.:
$data = array(
'January 3' => array (
'1:00 PM' => array (
'Doctor\'s Appt'
),
'4:45 pm' => array (
'Birthday Party',
'Something else at 4:45 as well'
)
)
);
(Your dates and times will probably not be those strings, but you get the idea.)
Then loop through dates and times in a natural way.
To create an indexed data structure like that shown above:
foreach ($dbResult as $row){
$data[$row['date']][$row['time']] = $row;
}
You can run a query which selects data for a given date. First, run a query which will give you a list of dates... something like this:
SELECT DISTINCT date FROM table;
Then do a foreach loop on the resulting list, running this query inside the loop:
SELECT time, name, about FROM table WHERE date = currentdate;
This will give you a list of the items for the current date, and you can simply iterate over them. It shouldn't be a performance problem if this is a single-user application or low-load web application.
If you prefer only one query, try this:
SELECT date, time, name, about FROM table ORDER BY date ASC, time ASC
You can then use a single foreach and a placeholder variable to loop over this, without the semantic hoop-jumping of multiple associative arrays and the like. Set the initial value of the placeholder value to the first date in the array, and then check on each loop to see if the date has changed. If it has, output a date header before you output the time, name, and notes about each entry, set the placeholder to the new date, and repeat.

Categories