Create PHP array's on the fly - php

I am having the worst time trying to get this to work. In the following code, I am gathering data from a database query and trying to build a muti-dimensional array object that will keep totals and tally up some information in a specific way. The problem is that instead of getting a value that is incrementing as it should, the value seems to be suffering from the last value it was assigned problem. Here is the code:
$REVIEWS = array();
$USER_REVIEWS = array();
$USER_IMGREVS = array();
pseudo-code: loop here which iterates over the DB results creating
$date - which is into this function as its called for each day of month
$p1user - which is one of the users (there are 3) 'levels' of users
$hr - is the hour which is built from the transaction's timestamp
$hr = date('H', $row['P1TIMESTAMP']);
$p1user = $row['P1USER'];
$REVIEWS[$date] += 1;
$USER_REVIEWS[$date][$p1user][$hr] += 1;
$USER_IMGREVS[$date][$p1user][$hr] += $row['F5'];
print "PASS1<br/>\n";
print "Value of Total Reviews: [".$REVIEWS[$date]."]<br/>\n";
print "Value of User Reviews: [".$USER_REVIEWS[$date][$p1user][$hr]."]<br/>\n";
print "Value of Reviewed Images: [".$USER_IMGREVS[$date][$p1user][$hr]."]<br/>\n";
print "<br/><br/>\n";
So - the 'total reviews' increments by one, as it should, for each time i print this. SO far so good. The next two arrays will only print the last values they were assigned, and will not be added together like they should. Why not? I have attempted to do this another way by literally creating the arrays one by one and assigning them in whole to the array containing them - but that also does not seem to work. Any insights?

i don't know how you initilize your array, maybe this will help:
// replace this 2 lines:
$USER_REVIEWS[$date][$p1user][$hr] += 1;
$USER_IMGREVS[$date][$p1user][$hr] += $row['F5'];
// with this code:
if (!isset($USER_REVIEWS[$date]))
$USER_REVIEWS[$date] = array();
if (!isset($USER_REVIEWS[$date][$p1user]))
$USER_REVIEWS[$date][$p1user] = array();
if (!isset($USER_REVIEWS[$date][$p1user][$hr]))
$USER_REVIEWS[$date][$p1user][$hr] = 0;
$USER_REVIEWS[$date][$p1user][$hr] += 1;
if (!isset($USER_IMGREVS[$date]))
$USER_IMGREVS[$date] = array();
if (!isset($USER_IMGREVS[$date][$p1user]))
$USER_IMGREVS[$date][$p1user] = array();
if (!isset($USER_IMGREVS[$date][$p1user][$hr]))
$USER_IMGREVS[$date][$p1user][$hr] = 0;
$USER_IMGREVS[$date][$p1user][$hr] += $row['F5'];

Sir, I dont understand very well why your coed is not working, but in my first test, I would change these lines:
$count = 1;
$USER_REVIEWS[$count][$p1user][$hr] += 1;
$USER_IMGREVS[$count][$p1user][$hr] += $row['F5'];
$count++;
Please, check if this code helps you anyway.

Your print statements for those values rely on the value of $p1user:
print "Value of User Reviews: [".$USER_REVIEWS[$date][$p1user][$hr]."]<br/>\n";
print "Value of Reviewed Images: [".$USER_IMGREVS[$date][$p1user][$hr]."]<br/>\n";
If you want to print it for all users you should loop over all possible users rather than just using $p1user. Either that or add them up if you want their sum.
Edit: Something that was bugging me was your data structure. It doesn't seem to represent your data very well. In your loop why don't you build up useful information that you store at the base of the review array?

Related

Structuring OOP Php methods and objects when using a JSON API call

I am making an application that pulls data through JSON with CURL. I'm using PHP and my script currently creates 2 different objects to contain the curl requests. I've got the data in a readable format, but I need to divide an average from the first call by an average from the second call.
This average is of equal relevance to each of the calls - and I'm new to working with objects and classes so am struggling to understand how to structure this in the right way. The following line of code doesn't work - but, if you read on it will hopefully help to explain what I'm trying to do.
$yield = object1->calculate_average($list)->average['price']/object2->calculate_average($list)->average['price'];
I want to code the $yield variable in to the listing class as a further method that will display when I call $anobject->yield. Should I access this via a) object1, b) object2, or c) it's own object (which seems excessive..as it will only be used occasionally). Is there a right way to do this, or does it not really matter?
My query is general (what is the best approach to using objects when an object appears to be as relevant to all options, and is it possible to reference arrays like this: calculate_average($list)->average['price']) as much as it is specific (how can I fix this script)
When this has come up before I've tended to just regrab the data from the source and fudge it, but because it's a JSON call and therefore takes a bit longer I've been prompted to find a better solution...
A simplified version of my best effort so far is below.
I've assumed that I need to use foreach on the json outputs:
class listing {
//This takes a stdClass object from the JSON and prepares it to be served
public function output_list($data) {
$price = "0";
$vals = "0";
$list = array();
foreach ($data->listing as $item) {
//Calculate average price
$price = $price + $item->price;
$vals = $vals + 1;
//Display information about each item
$list[$vals][] = "Price: £" . $item->price . " and various data";
$list[$vals][] = ...;
}
return $list;
}
// This function calculates equations on the data which I read above
public function calculate_average($list) {
$average = array();
$total_price = array_column($list, '1'); //Find the total sum of list[?][1] which = price
$vals = count($list); //count the number of values in the list
$average['denominator'] = $vals;
$average['week'] = $total_price / $average['denominator'];
//And a number of other calculations within the array...
return $average;
}
}
I then want to call these by using the following code:
$object1 = new listing();
$list1 = $object1->output_list($response); ////Output formatted data
print_r($list1);
$average = $object1->calculate_average($list);
$object2 = new listing();
$list2 = $object2->output_list($response); ////Output formatted data
print_r($list2);
$average = $object2->calculate_average($list);
The other thing is that $total_price = array_column($list,'1') needs me to have php 5.5 - which I don't have, so I need to find an alternative - and that makes me question whether my array approach is the right one in the first place. [I need to sum every [?][1] reference in the multi-dimensional array I've made].
If you're able to help I'd be so grateful - I've been trying to get my head around objects and classes for weeks!

Array is reassigning previous values into unset locations, PHP

I am trying to create a multidimensional array at run-time that queries and stores several MySQL results. For instance, let us say we have a table like so (is fictional, so please don't pick at the example):
**store--tag--color--size**
1--101--blue--s
2--102--red--s
2--103--yellow -- m
3--104--blue--m
The need is to create an multi-d array that will store all the products per store. The result I would like is:
$storeArray = array[[[101],[blue],[s]],[[102,103],[red,yellow],[s,m]],[[104],[blue],[m]]];
here is the code I have:
$counter = 0;
foreach($storeIDs as $item){
$result = mysql_query('select whatever');
$rows = mysql_num_rows($result);
for($i=0;$i<$rows;$i++){
$tag[$i] = mysql_result();
$color[$i] = mysql_result();
$size[$i] = mysql_result();
}
$tempArray = array($tag,$,$color,$size);
$storeArray[$counter] = $tempArray;
unset($tempArray);
$counter++;
}
The problem is, even though I have unset $tempArray, the third loop which should capture just
[[104],[blue],[m]]
actually stores
[[104,103],[blue,yellow],[m,m]].
I've tried setting $tempArray to array(), or array(array()). The data from the second loop always spills over into ANY future iteration that is of smaller size.
How can I get $storeArray to look like the goal above?
Thank you
You're unsetting $tmpArray, but it looks like you may need to also unset $tag, $color, and $size as well. There are better approaches with a slightly different data structure, but as is, have you tried this?
unset($tempArray,$tag,$color,$size);
Effectively, you might set $tag[0] and $tag[1] in a loop that has two items. Then, for a loop that has one item you update $tag[0], but $tag[1] remains set.

Count amount of similar items in array, return value if under 3

I have an array which contains sets of three similar named items; however, sometimes there's only two items in a set and I want to call these out.
<?php
$items = array(
'reviewpitfighter-1.138x88.jpg',
'reviewpitfighter-2.138x88.jpg',
'reviewpopfulmailsegacd-1.138x92.jpg',
'reviewpopfulmailsegacd-2.138x76.jpg',
'reviewpopfulmailsegacd-3.138x97.jpg'
);
?>
You'll note that there are two reviewpitfigher* items, and three reviewpopfulmailsegacd* items. I've started down a rabbit hole of loops and feel that there is something simple I'm just glossing over.
May be you can do this as a 2 stage process.
Stage 1:
Loop through the original array and form another set of array with its key as the value of this original array. Then save the repetition count in each of those new arrays.
Stage 2:
Loop through the new set of arrays and then pick out the arrays which has values less than 3 and retrieve its key.
Hope this helps!!
Here's the solution I came up with, sorry it took so long to post.
foreach($images as $value){
$lastItem = explode('-', $images[$count - 1]);
$parts = explode('-', $value);
if(preg_match('/^1/', $parts[1]) && $count != 0){
if(preg_match('/^2/',$lastItem[1])){
$imgurl = preg_replace('/^p?review/','',$lastItem[0]);
$sql = 'SELECT field FROM table WHERE field = "' . $imgurl . '"';
$result = $dbConn->FetchArray($dbConn->Query($sql), MYSQL_ASSOC);
$array[$imgurl] = $result;
}
}
$count++;
}
I get an array of all the images, then I check to see if I'm looking at the first image, if I am then I see if the last image I looked at was the second image. At this point I then call into the database to get some information to display a neatly messaged out put of what reviews are missing a third image. In the end $array contains this list which I can loop over.

How Do I store my POST While Loop

Let me know if you want more details but:
I have an different number of inserts I need to make based on a POST form data that I created in a loop.
If I were to write it all out it would look like this:
$Scout1=$_POST['ScoutID1'];
$Scout2=$_POST['ScoutID2'];
and it keeps going until it reaches "x" I do have that number stored as
$ScoutCount
(so if the above code would post all the variables I brought over {$ScoutCount=2}
I can't find a way to do:
while (X>0){
$ScoutX=$_POST['ScoutIDX'];
X--;
}
how can I do this?
You might be looking for variable variables
But rather, I would recommend storing the data in an array, as opposed to individual variables. Then in a for loop, it could look like:
$scouts = array();
for ($i = 0; $i < 10; $i++)
{
$scouts[$i] = $_POST['ScoutID' . $i];
}
or something.
instead of having form fields called ScoutID1, ScoutID2 wtc name them
name="ScoutID[]"
then you will have a nice array with work with
//put scoutIDs into Array
$scouts = array();
for ($i = 1; $i <= $ScoutCount; $i++)
{
$scouts[$i] = $_POST['ScoutID' . $i];
}
Thanks - that may have seemed easy but I wasted a day trying to figure it out. thanks from the newbie to Php....

php: add array placement number to each array set e.g. 1 2 3

I have a data set from mysql in a multidimensional array.
I am using a pagination script to show 10 per page of that array. I want to know how to append a number to each one like a scoring system. The array is sorted by the way that it will aways be so i want to to add a 1 to the first item, a 2 to the second item and so on.
I dont want to do this in the foreach that i output since this will not translate over to the second page where it would start back at 1.
Any ideas on how to attach a number in desc order to each item in the array so i can access it in the foreach and display it?
Thanks in advance
Use the same math used to find the offset in your pagination query and start counting from there.
fist you need to save the indexes in a $_SESSION variable:
$_SESSION['indexes'] = array();
and for multidimentional:
foreach( $array as $index=>$arrValue) {
echo $index;
foreach($arrValue as $index2=>$value){
echo $index2;
$_SESSION['indexes'][$index][$index2] = $value;
echo $value;
}
}
than you can go through all of the session indexes; where $index is the page or $index2 can be the row
I figured it out by doing some calculations based on which page i was on and the page count that was set and finding the size of the array from the db:
$all_members = get_users_ordered_by_meta('metavalue', 'desc');
$array_count = count($all_members);
$posts_per_page = get_option('posts_per_page');
if ($page > 0) {
$total_posts_avalible = ($posts_per_page * $page);
$usernum = $total_posts_avalible - $posts_per_page;
}
Then i echo the $usernum in the foreach next to the name of the user.
foreach() {
$usernum++;
echo $usernum; echo $user_name;
}

Categories