Get array value and put it into a variable (multidimensional array?) - php

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'"

Related

weird behavior of json_encode function

I have this normal array name $arr..
and trying to push something on the array using array_push() function.. like array_push( $arr['alerts_data'], 999 );
It produces this output:
Array
(
[alerts_data] => Array
(
[0] => 169
[1] => 175
[2] => 111
[3] => 48
[4] => 999
)
)
When i use json_encode I got:
{"alerts_data":[169,175,111,48,111,999]}
BUT, when I try to unset() something from $arr like:
unset( $arr['alerts_data'][4] );// will remove removes the 999
and then use the json_encode again, I got this json object
{"alerts_data":{"0":169,"1":175,"2":111,"3":48}}
What's wrong in here? can you tell? I want to achieve the first encoded json above by using the unset() function.
Yes, it's because the array keys aren't consecutive anymore, so it's treated as an associative array, and PHP associative arrays become JavaScript objects, because JavaScript does not have associative arrays.
Use array_splice() to cleanly remove elements from the array.
You have a gap in your keys (it goes from 3 to 5), so an object must be created for it to be valid. Two possible solutions:
array_splice($arr['alerts_data'], 4, 1);
unset($arr['alerts_data'][4]);
$arr['alerts_data'] = array_values($arr['alerts_data']);

Navigating a multidimensional array with dynamic

I'm trying to figure out why it is that I cannot access the follow array with this statement:
var_dump($thevar[0]['product_id']);
Array
(
[d142d425a5487967a914b6579428d64b] => Array
(
[product_id] => 253
[variation_id] =>
[variation] =>
[quantity] => 1
[data] => WC_Product Object
(
[id] => 253
[product_custom_fields] => Array
(
[_edit_last] => Array
(
[0] => 1
)
[_edit_lock] => Array
(
[0] => 1345655854:1
)
[_thumbnail_id] => Array
(
[0] => 102
)
I can, however, access the 'product_id' using the dynamically created array name:
print_r($thevar['d142d425a5487967a914b6579428d64b']['product_id']);
The issue is, I don't know what that dynamic name is going to be on the fly...
There are several options for such scenarios.
Manually iterate over the array
You can use reset, next, key and/or each to iterate over the array (perhaps partially).
For example, to grab the first item regardless of key:
$item = reset($thevar);
Reindex the array
Sometimes it's just convenient to be able to index into the array numerically, and a small performance hit is not a problem. In that case you can reindex using array_values:
$values = array_values($thevar);
$item = $values[0]; // because $values is numerically indexed
Iterate with foreach
This would work for a single value as well as it works for more, but it might give the wrong impression to readers of the code.
foreach($thevar as $item) {
// do something with $item
}
If the array key is dynamic you might find the PHP function array_keys() useful.
It will return an array of the keys used in an array. You can then use this to access a particular element in the array.
See here for more:
http://php.net/manual/en/function.array-keys.php
Because PHP array are associative therefor you have to access them by key.
But you may use reset($thevar) to get first item.
Or array_values():
array_values($thevar)[0]
Or if you feel like overkill you may also use array_keys() and use the [0] element to address element like this:
$thevar[ array_keys($thevar)[0]]

how to split this array

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'];

how to create a multidimensional array PHP

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.

How do i get passed an empty key in a php array

how to i get to the arrays content if it doesnt have a key like this
$products[0]
this will get me partially there but how to i get past []
( [0] => Array
( [] => Array (
[0] => Array ( [product_name] => stuff i need to get to )
That is very strange. You could try
$products[0][''][0]['product_name']
Use var_dump or var_export to print your array and you will see its an empty string.
print_r will give you output like that for empty strings.
$products[0][""][0]["product_name"]

Categories