I have some data for my sites statistics in a SQL DB:
date: visits: pageviews:
12-12-12 34 21
12-12-13 31 22
12-12-14 33 2445
12-12-15 35 2422
12-12-16 36 232
//ect ect
I'm trying to create a Multidimensional array that contains all the dates info from the DB and where the date will be the key (selector,name of the array inside the multi array), so as the end result, I should be able to just do this:
print_r $my_multi_array[12-05-12];
And I should see the statistics for that date on the screen.
Now I know how to do all the loops and stuff, and I even have a good idea about how to do multidimensional arrays, it's just that I think I'm doing something wrong:
//first things first, define the array:
$my_multi_array=array();
//then, in a loop, append to the array:
$my_multi_array[]=array("$date"=>array('visits'=>mysql_num_rows($visit_query),'pageviews'=>$pageview_query));
Now when I print_r that array, everything looks good:
Array ( [0] => Array ( [11-12-24] => Array ( [visits] => 1 [pageviews] => 0) ) [1] => Array ( [11-12-25] => Array ( [visits] => 1 [pageviews] => 0) ) [2] => Array ( [11-12-26] => Array ( [visits] => 1 [pageviews] => 0)))1
Notice the 1 at the end ^^. That seemed to be in the result (not a typo).
Now when I try printing a certain array out (using the date as the key):
print_r $my_multi_array['11-12-24'];
I get:
1
So then i try:
print_r $my_multi_array[2];
and that works fine.
For some reason, it wont let me select an array from $my_multi_array using the date as the key.
Any ideas on how to fix this?
thanks
Everything is correct, because you don't have array('key' => 'value') style array, instead of that you've got array( [0] => array( 'key' => 'value' ) ) that's why you're getting correct result on accessing numeric key of the array.
You have to put the date as the array key, like so:
$my_multi_array[$date]=array("$date"=>array('visits'=>mysql_num_rows($visit_query),'pageviews'=>$pageview_query));
Notice the $my_multi_array[$date].
By doing $my_multi_array[] = ... you are just creating a new numerical index on the array with the content on the right side. That's why when you access the array with the numerical index, like $my_multi_array[2], it works.
On the other hand, by doing $my_multi_array[$date]you are treating the array like an hash table, where you associate a key (in this case a string containing a date) with a value.
Related
When a print_r() an array $stats, I get the following:
Array ( [0] => Array ( [like] => 71 [dislike] => 372 [total] => 443 [like_s] => 78 [dislike_s] => 291 [total_s] => 369 [final] => 11 ))
I want to get the [dislike_s] value and put it into a variable.
I have attempted this:
$statss = $stats['dislike_s'];
But it did not work. I have also tried $statss = $stats['dislike_s'][0]; without result.
What am I doing wrong?
You are missing a level of your array
Array ( [0] => Array ( [like] => 71
//^ this level
Also you are using the wrong variable, as you said your array is stored in $stats so
$total_revision = $stats[0]['dislike_s'];
$stats is a two dimensional Array, i.e. it is an array of arrays. You can see this from the output of print_r. You have something that looks like `Array ( [0]=>Array(...)). Therefore, when accessing an element of the inside array, you can think of it like this:
$inner_array=$stats[0];
$total_revisions=$inner_array['dislike_s'];
Php gives you a shorthand for combining these steps(pretty much all languages do) and it looks like $total_revisions=$stats[0]['dislike_s'] but intuitively it's the same thing. You're saying "in the array $stats[0] give back the value of array element 'dislike_s'"
Just a quick one i need to get a value from an array the array is made like this
$resultOfAdd[“CaseAndMatterResult”][“ResultInfo”][“ReturnCode”];
and it gives an output of this
Array (
[AddCaseAndMatterResult] => Array (
[ResultInfo] => Array (
[ReturnCode] => OK
[Errors] =>
[Warnings] =>
)
[CaseID] => 4880062
[MatterID] => 4950481
[LeadID] => 0
[CustomerID] => 0
)
)
All i want to do is put the part "MatterID" into a variable. how would I achieve this.
i have tried
$matterID = array($resultOfAdd["MatterID"]);
and this does not work
Regards
This is a multi-dimensional, associative array. Think of it like floors of a building. The key MatterID does not live in the first dimension (floor), rather on the second, in the AddCaseAndMatterResult sub-array.
$matterID = $resultOfAdd['AddCaseAndMatterResult']['MatterID']
Successive dimensions of an array are specified with successive square-brackets, each naming the key to look in (this is true of most languages).
$matterID = $yourArray['AddCaseAndMatterResult']['MatterID'];
Use this way:
$matterID = $resultOfAdd['AddCaseAndMatterResult']['MatterID'];
I'm a bit struggling with the associative arrays in associative arrays. Point is that I always have to drill deeper in an array and I just don't get this right.
$array['sections']['items'][] = array (
'ident' => $item->attributes()->ident,
'type' => $questionType,
'title' => $item->attributes()->title,
'objective' => (string) $item->objectives->material->mattext,
'question' => (string) $item->presentation->material->mattext,
'possibilities' => array (
// is this even neccesary to tell an empty array will come here??
//(string) $item->presentation->response_lid->render_choice->flow_label->response_label->attributes()->ident => (string) $item->presentation->response_lid->render_choice->flow_label->response_label->material->mattext
)
);
foreach ($item->presentation->response_lid->render_choice->children() as $flow_label) {
$array['sections']['items']['possibilities'][] = array (
(string) $flow_label->response_label->attributes()->ident => (string) $flow_label->response_label->material->mattext
);
}
So 'possibilities' => array() contains an array and if I put a value in it like the comment illustrates I get what I need. But an array contains multiple values so I am trying to put multiple values on the position $array['sections']['items']['possibilities'][]
But this outputs that the values are stores on a different level.
...
[items] => Array
(
[0] => Array
(
[ident] => SimpleXMLElement Object
(
[0] => QTIEDIT:SCQ:1000015312
)
[type] => SCQ
...
[possibilities] => Array
(
)
)
[possibilities] => Array
(
[0] => Array
(
[1000015317] => 500 bytes
)
[1] => Array
...
What am trying to accomplish is with my foreach code above is the first [possibilities] => Array is containing the information of the second. And of course that the second will disappear.
Your $array['sections']['items'] is an array of items, so you need to specify which item to add the possibilities to:
$array['sections']['items'][$i]['possibilities'][]
Where $i is a counter in your loop.
Right now you are appending the Arrays to [items]. But you want to append them to a child element of [items]:
You do:
$array['sections']['items']['possibilities'][] = ...
But it should be something like:
$array['sections']['items'][0]['possibilities'][] = ...
$array['sections']['items'] is an array of items, and as per the way you populate the possibilities key, each item will have it's own possibilities. So, to access the possibilities of the item that is being looped over, you need to specify which one from $array['sections']['items'] by passing the index as explained in the first answer.
OR
To make things simpler, you can try
Save the item array (RHS of the first =) to a separate variable instead of defining and appending to the main array at the same time.
Set the possibilities of that variable.
Append that variable to the main $array['sections']['items']
I have:
array[{IsChecked: true, SEC: 0, STP: 0},
{IsChecked: ture ,SEC: 0, STP: 1},
{IsChecked: false, SEC: 1 ,STP: 0}]
How to get each SEC where IsCheked value is true?
I am pulling some data from a mysql table via the following:
$result = mysql_query("SELECT characters_ID, name, borndate, deathdate, marrieddate, ispregnant FROM characters WHERE isfemale='1'",$db);
$femaledata = array();
while ($row_user = mysql_fetch_assoc($result))
$femaledata[] = $row_user;
This gives me an array that looks like this:
Array (
[0] => Array ( [characters_ID] => 2 [name] => Helene [borndate] => 35 [deathdate] => 431 [marrieddate] => 157 [ispregnant] => 0 )
[1] => Array ( [characters_ID] => 4 [name] => Isabelle [borndate] => 161 [deathdate] => [marrieddate] => 303 [ispregnant] => 1 )
[2] => Array ( [characters_ID] => 7 [name] => Helene [borndate] => 326 [deathdate] => [marrieddate] => [ispregnant] => 0 )
[3] => Array ( [characters_ID] => 72 [name] => Faylinn [borndate] => 335 [deathdate] => [marrieddate] => [ispregnant] => 0 )
[4] => Array ( [characters_ID] => 74 [name] => Relina [borndate] => 349 [deathdate] => [marrieddate] => [ispregnant] => 0 )
)
Now I need to remove any characters who have a value for deathdate or ispregnant, and then I need to run some code on the others. For instance I need to grab the borndate value, compare it to the current date to find age, and based partly on age, I need to run code for each to determine if the character has become pregnant on the turn.
Apologies that this seems like a long-reaching question. Multidimensional arrays still seem to confound me.
Edit: (question needs to be more clear)
Can you please suggest the best way that I would either explode or break up the array, and then do conditional modification to the data, or instead how I could remove unneeded data and then do conditional modification to the data.
My ultimate output here would be taking suitable female characters (not dead or pregnant already), and based on their age, giving them a chance at becoming pregnant. If true, I'd throw some code back at the SQL database to update that character.
Thanks!
All the things you need could probably get done with SQL :
Now I need to remove any characters who have a value for deathdate or
ispregnant
Simply add some argument to your WHERE condition :
isPregnant IS NULL AND deathdate IS NULL
For instance I need to grab the borndate value, compare it to the
current date to find age
Depending of your field format the maths could be done in SQL , have look to the DATE function of mysql
Don't underestimate the power of your sql server , 99% of the time it is probably faster than php to work on data set.
Instead if immediately removing some rows from your array, try limiting the data you recieve through SQL.
You can loop through your array like this:
foreach($femaledata as $female)
{
echo $female['name'];
}
do you mean something like this?
$femaledata = array();
while ($row_user = mysql_fetch_assoc($result)) {
$ok = false;
// do you validation for every user
if($ok) array_push($femaledata,$row_user);
}
TJHeuvel gave you the right answer, and you should accept that answer. However, to inform: multidimensional arrays need not confound. Let me see if I can explain.
In PHP, you can put any object at all into an array, including other arrays. So, let's say you have an array that contains other arrays. When you iterate over that array using a looping construct (usually a foreach loop), each iteration of the loop will give you another array; if you want to access the elements of this sub-array, just loop over it. This is called a nested loop. Example:
$r = array(
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
foreach ($r as $cur) {
foreach ($cur as $num) {
echo $num;
}
}
In each iteration of the outer loop, $cur contains an array; the inner loop iterates over contents of this array. This technique allows you to process arrays of any dimension.
However, in your specific case, you don't need to use an inner loop to iterate over your subarrays. You only need to access certain elements of your subarrays by their keys, rather that processing all of them in turn. So, a simple foreach loop will do.
I have a page that searches a database and generates the following array. I'd like to be able to loop through the array and pick out the value next assigned to the key "contact_id" and do something with it, but I have no idea how to get down to that level of the array.
The array is dynamically generated, so depending on what I search for the index numbers under "values" will change accordingly.
I'm thinking I have to do a foreach starting under values, but I don't know how to start a foreach at a sublevel of an array.
Array (
[is_error] => 0
[version] => 3
[count] => 2
[values] => Array (
[556053] => Array (
[contact_id] => 556053
[contact_type] => Individual
[first_name] => Brian
[last_name] => YYY
[contact_is_deleted] => 0
)
[596945] => Array (
[contact_id] => 596945
[contact_type] => Individual
[first_name] => Brian
[last_name] => XXX
[contact_is_deleted] => 0
)
)
)
I've looked at the following post, but it seems to only address the situation where the array indices are sequential.
Multidimensional array - how to get specific values from sub-array
Any ideas?
Brian
You are correct in your assumption. You could do something like this:
foreach($array['values'] as $key => $values) {
print $values['contact_id'];
}
That should demonstrate starting at a sub level. I would also add in your checks to see if its empty and if its an array... etc.
Another hint regarding syntax - if the array in your original example is called $a, then the values you want are here:
$a['values'][556053]['contact_id']
and here:
$a['values'][596945]['contact_id']
So if there's no additional structure in your array, then this loop is probably what you want:
foreach ($a['values'] as $toplevel_id => $record_data) {
print "for toplevel_id=[$toplevel_id], contact_id=[" . $record_data['contact_id'] . "]\n";
}
foreach($array['values'] as $sub_arr){
echo $sub_arr['contact_id'];
}