Array confusion with square brackets - php

I am using an API which has a lot of data inside lots of arrays which as you may know can be quite confusing.I am relatively new to API's and this one in particular has no documentation.
My code below is grabbing the recent_games() function which is pulling the whole API then I am using foreach loops to get inside the data.
$games = $player->recent_games();
foreach($games['gameStatistics']['array'] as $key => $gameStatistic) {
$game_date[strtotime($gameStatistic['createDate'])] = $gameStatistic;
}
// order data
krsort($game_date);
foreach ($game_date as $game => $data) {
$statistics[$data] = $data['statistics'];
}
I am getting errors such as illegal offset for:
$statistics[$data] = $data['statistics'];
Is there a way to continue down the nesting of arrays ($game_date) to get to the data that I need?
Let me know if you need more info.
Thanks
EDIT more info:
The first foreach loop at the top loops a unix timestamp key per game. Looks like this:
[1370947566] => Array
(
[skinName] => Skin_name
[ranked] => 1
[statistics] => Array
(
[array] => Array
(
[0] => Array
(
[statType] => stat_data
[value] => 1234
)
[1] => Array
(
[statType] => stat_data
[value] => 1234
)
As you can see its quite nested but I am trying to get to the individual statistics array. I hope that helps?

$statistics[$data] = $data['statistics'];
There is absolutely no way this line is correct.
The right hand side uses $data as if it were an array, indexing into it. The left hand side uses $data as a key into an array. Since the only valid types for keys are strings and integers, $data cannot satisfy the requirements of both expressions at the same time -- it cannot be an array and a string or integer.
It's obvious from the error message that $data is in fact an array, so using it as $staticstics[$data] is wrong. What do you want $statistics to be?

Related

PHP using key of one array to access same key position on another array

I've looked at a number of suggestions for this, and they seem to rely on array_combine() which unfortunately is not suitable, as they arrays need to stay separate for other functions.
The arrays are set out as per
Array ( [0] => 3 [1] => 1 [2] => 3 )
Array ( [0] => 194 [1] => 0 [2] => 452 )
When I read in the first array, I get the key as $key and everything works fine.
Whenever I try and access the second array the whole script just whites out the page.
I want the code to work simliar to this ...
$a2value = $a2[$key] => $value;
echo $a2value;
Then I can do SQL lookups using $a2value
Any help would be appreciated
Here Try this
let's suppose two arrays of same number of elements
$a1=[1,2,3];
$a2=[194,0,452];
//A Simple foreach
foreach($a1 as $key=>$a1value){
$a2value=$a2[$key];
//Perform Query here
}
Remember one thing number of elements of both array should always be equal or it will cause an error
If you aren't certain about the size of both arrays then replace the line with this code
$a2value=empty($a2[$key]) ? null : $a2[$key];
Hope this works !!!

Unable to convert array according to date time value in php

I have a array named $itemIds and it consists of the following datas. The key is the items id and the value is the date time that can be converted to a readable date.What I want to do is simply sort the order of the array according to the value (time). I'm totally new to php and some examples or tips would be great ! I would love to hear from you.
Array
(
[10477] => 1508898726
[10549] => 1508898744
[10891] => 1508898752
)
If I use this code I get the following data from the print_r.
if (isset($itemIds)) {
$time = array();
foreach ($itemIds as $key => $val) {
print_r($key.'=>'.date('m/d/Y H:i:s', $val));
}
}
The problem starts from here.I want to sort(asc & desc) the $itemsIds according to the date time.
10477 => 10/25/2017 11:32:06
10549 => 10/25/2017 11:32:24
10891 => 10/25/2017 11:32:32
I want to sort the data then use array_keys($shopIds) to change it like the following data
Array
(
[0] => 10477
[1] => 10549
[2] => 10891
)
I think the easier approach would be to sort the data and then flip it so the keys are values. If you look at your data you are initially dealing with actual timestamps from what I can see. Use them, don't change them to strings. I say this because you are just causing yourself to do extra work without any reason and introducing a layer of complexity that is not needed. Instead I would do the following:
$array = [
10477 => 1508898726,
10549 => 1508898744,
10891 => 1508898752,
];
arsort($array);
$sorted_array = array_values(array_flip($array));
This is easy to read and does not involve the extra function. The result you are left with is:
Array
(
[0] => 10477
[1] => 10549
[2] => 10891
)
A little explanation:
I am using arsort() or asort() (based on the direction you want to sort) in order to sort based on the values in the array.
Then I use array_flip() on the array in order to swap the keys and values.
And last I am using array_keys() to reset the indexes in the array and maintain its sort.
Hope this helps!

http_build_query() dot is converted to underscore

Please check the below array:
Array([bunrey] => Array ([0] => 20130730181908615391000000)
[mt.shasta] => Array (
[0] => 20130708203742347410000000
[1] => 20130213201456984069000000
[2] => 20130712144459481348000000
)
[shingletwon] => Array
(
[0] => 20130801233842122771000000
)
)
I want to send this array as query string using http_build_query(),
I got the below string after using http_build_query():
bunrey%5B0%5D=20130730181908615391000000&mt.shasta%5B0%5D=20130708203742347410000000&mt.shasta%5B1%5D=20130213201456984069000000&mt.shasta%5B2%5D=20130712144459481348000000&shingletwon%5B0%5D=20130801233842122771000000
As you can see after sending this query string to some other file, there I am trying to retrieve. I had echoed the $_REQUEST object:
Array (
[bunrey] => Array
(
[0] => 20130730181908615391000000
)
[mt_shasta] => Array
(
[0] => 20130708203742347410000000
[1] => 20130213201456984069000000
[2] => 20130712144459481348000000
)
[shingletwon] => Array
(
[0] => 20130801233842122771000000
)
)
please check one of the key mr.shasta had changed to mr_shasta.
Can you people please provide any solution for this.
This is the standard PHP behaviour. Points are converted in underscores when used as array keys in a POST request.
From the documentation:
Dots and spaces in variable names are converted to underscores. For
example < input name="a.b" /> becomes $_REQUEST["a_b"].
The only solution is: stop using spaces and/or dots in array keys when using them in POST requests or, else, operate a string replace on every array key your receive.
$post = array();
foreach ($_POST as $key => $value)
$post[str_replace("_", ".", $key)] = $value;
Note that the code above would fix only the problem of . (converted to _) but not spaces. Also, if you have any _ in your original key this would be converted to . as well (as pointed out in the comments).
As you can see, the only real solution is to avoid . and spaces in $_POST keys. They just can't be received, not with PHP (and not with other server-side solutions that I know of): you'll loose that information.
No, this is not a limitation or a crap feature: this is a programming guideline. If you're using array keys names for something more than what you would normally do with a variable name, you're most likely doing something conceptually wrong (and I've done it many times too).
Just to give you an example on how wrong is that: in some programming solutions like asp.net-mvc (and, I think, codeigniter too) POST/GET requests are supposed to be mapped over functions in what's called a "controller". Which means that if you send a POST which looks like ["myKey" => "myValue", "myOtherKey" => "someValue"] you should then have a function which takes keys as arguments.
function(String myKey, String myOtherKey){ }
PHP have no default "on-top" framework (that I know of) which do this: it allows you to access $_POST directly. Cool: but this toy can breake easely. Use it with caution.
I may be wrong here, but I've replicated what you're doing and have found it depends how you assign the array as to whether or not it changes the key like this:
//doesn't change to mt_shasta
$array['bunrey'][0] = 20130730181908615391000000;
$array['bunrey']['mt.shasta'][0] = 20130708203742347410000000;
$array['bunrey']['mt.shasta'][1] = 20130708203742347410000000;
$array['bunrey']['mt.shasta'][2] = 20130708203742347410000000;
$array['bunrey']['shingletwon'][0] = 20130708203742347410000000;
//does change to mt_shasta
$array = array (
'0' => 20130730181908615391000000,
'mt.shasta' => array (
0 => 20130708203742347410000000,
1 => 20130213201456984069000000,
2 => 20130712144459481348000000,
),
'shingletwon' => array
(
0 => 20130801233842122771000000,
),
);

Store an array to an array key

I'm trying to store an array ($temp) into the $data array, where key is prices.
$data['prices'] = $temp;
However, PHP converts the array into string instead and is throwing me and error.
Notice: Array to string conversion
Is $data = array('prices' => $temp); the only solution?
edit:
I found my mistake. Yes, $data was used previously as a string that's why PHP is converting the input into string.
Problem 2, doing a print_r on $data['prices'] = $xml->result->Prices->Price, shows only 1 set of array. But I am able to retrive 2 sets of result by doing a foreach loop on $data['prices']. Why is that so?
Content of $temp http://pastebin.com/ZrmnKUPB
Let me be more clear..
The full xml object I'm trying to extract information from: http://pastebin.com/AuMJiyrw
I'm only interested in the price array (Price_strCode and Price_strDescription) and store them in $data['prices']. End result something like this:
Array(
[0] => (
[Price_strCode] => 0001
[Price_strDescription] => Gold
)
[1] => (
[Price_strCode] => 0002
[Price_strDescription] => Silver
)
)
Unless you are doing some other array to string conversion elsewhere, the array is actually being stored as another array.
$data['prices'] will be an array, which can be accessed as $data['prices']['key'].
This is not possible, I have been doing this always and it works fine. You must be doing something else somewhere which is causing your array to convert to strong. share your code here

manipulate multiarrays

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.

Categories