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,
),
);
Related
I have following code block in PHP:
$params = array(
'wsKey' => '5443',
'Number' => array('226340656'));
I want to convert above PHP code to AutoIt code. I tried below code
Local $params[2][2] = [['wsKey', '5443'], ['Number', '226340656']]
is it correct?
It seams that you cannot create the same structure on AutoIt because demonstrated structure could be represented with hashmap(php's arrays are hashmap) only. And AutoIt has none of any datatype that related to hashmap (arrays only).
But you could try to find (or write) library which provides bunch of functions which help to work with variable like with hashmap(example)
First of all, your question is not clear, and the following format is wrong,
$params[2][2] = [['wsKey', '5443'], ['Number', '226340656']]
if you want to create $params[2][2] array with {{'wsKey', '5443'}, {'Number', '226340656'} data you can use the following code segment.
$params[] = array('wsKey', '5443');
$params[] = array('Number', '226340656');
If print $params then following out put will display,
Array
(
[0] => Array
(
[0] => wsKey
[1] => 5443
)
[1] => Array
(
[0] => Number
[1] => 226340656
)
)
I have seen many posts on here about converting a multi dimensional array into a string but not the other way around so I have a question to ask. I have got the following string of data which is retrieved from a JQuery array via a post:
["enquiry#gardengamesltd.co.uk, sales#gardengamesltd.co.uk","http://www.gardengamesltd.co.uk/acatalog/contactus.html"],["enquiry#gardengames.com","http://www.gardengames.com/contact/"],["info#gardengamesandleisure.com","http://www.gardengamesandleisure.com/ContactUs.aspx"],["playtime#kentgardengameshire.com","http://www.kentgardengameshire.com/contact-us.html"],["sales#gardengamesuk.com","http://www.gardengamesuk.com/contact.php"],["team#gardenknightgames.com","http://www.gardenknightgames.com/contact/"],["ajax-loader#2x.gif","http://www.just-garden-games.co.uk/"]
What I am wanting to do is convert it into an array which looks like so:
Array
(
[0] => Array
(
[Email] => enquiry#gardengamesltd.co.uk, sales#gardengamesltd.co.uk
[FB] => http://www.gardengamesltd.co.uk/acatalog/contactus.html
)
[1] => Array
(
[Email] => enquiry#gardengames.com
[FB] => http://www.gardengames.com/contact/
)
[2] => Array
(
[Email] => info#aaeventhire.com
[FB] => http://www.aaeventhire.com/pricing/garden-games
)
)
I realize I could use $array = explode('","', $harvest_data); however this is only going to give me a single level array and ideally I am wanting to keep email, fb inside an inner array.
Has anyone got any ideas on how I can go about doing this?
Thanks.
As it is, your string is not valid JSON. Wrapping it in a pair of []'s would work in this case so if the input always has this form, this would work:
$json_string = '[' . $your_string . ']';
$your_array = json_decode($json_string);
However, it would be best to make sure that your front-end / javascript posts valid JSON to begin with.
Working example.
I've searched a lot for this, and found several similar questions, but none quite address what I'm trying to accomplish.
I'm trying to write a code that will search a PHP (multi)multidimensional array to see which subarray contains the unique key value that I have. Then I would like it to return the value of a different key in that same object subarray.
$Arraytosearch = Array(
.
//various other subarrays
.
[fields] => Array (
.
.
.
//I don't know the number of the object subarray
[x] => PodioTextItemField Object (
[__attributes] => Array (
[field_id] => 37325091
[type] => text
[external_id] => id
[label] => ID
[values] => Array (
[0] => Array (
[value] => REF100019 ) )
[config] => Array (
[description] => [settings] => Array (
[size] => small )
[required] => [mapping] => [label] => ID [visible] => 1 [delta] => 2 ) )
.
.
.
//(and so on)
I'd like to write a function that will return "REF100019" by supplying the value of the field_id => 37325091.
Some things I have tried that I couldn't get to work:
foreach
and new RecursiveIterator although the tutorials I read weren't useful for my case here.
Even though the array looks complicated, I think it will be easy since I already have the field id of the parent array.
Thank you in advance for any guidance or sample codes that will work!
Background: This is a part of the response I get from Podio after submitting a request to their API. I just don't know how to take that response and get the piece I need (the ID) so that I can echo it for users).
EDIT: Thank you Orangepill and Barmar for the support. I tried your code. But was getting an error, which made me realize I hadn't given you the full array. I figured out how to get the Podio response to display in a more readable format (I was reading the full JSON response before from the Podio debug file which was super confusing), and figured out the full array is actually structured as I have shown below.
I then took your code and was able to figure out how to make it work for my scenario (see below). Very proud of myself considering I have never written any code before, but I couldn't have done it without your help! Thanks again!
$Arraytosearch = Array(
[items] => Array(
[0] => PodioItem Object(
[_attributes] => Array(
[fields] => Array (
[x] => PodioTextItemField Object (
[__attributes] => Array(
[field_id] => 37325091
[values] => Array(
[0] => Array(
[value] => REF100019 ) )
Note: For anyone who is new to programming like myself and wants the Podio response (or any JSON string) to display in a "pretty" readable format like above, use the code (from Display an array in a readable/hierarchical format thanks to Phenex):
print "<pre>";
print_r($Arraytoformat);
print "</pre>";
And finally, the full code I used (using Orangepill's answer below) which searches the objects and arrays and gives me what I have been searching for for days now is as follows:
$Arraytosearch = PodioItem::filter(APP_ID, $filterParams);
$fieldID = 37325091;
function getFirstValueByFieldId($fieldId, $Arraytosearch){
foreach($Arraytosearch["items"][0]->__attributes["fields"] as $textitem){
if ($textitem->__attributes["field_id"] == $fieldId){
return $textitem->__attributes["values"][0]["value"];
}}}
$refID = getFirstValueByFieldId($fieldID, $Arraytosearch);
The podio-php library has built-in methods that handle all this for you. There's no need to mess with the __attributes property yourself.
You can see a bunch of examples at https://github.com/podio/podio-php/blob/master/examples/items.php
In your case:
// Get item collection
$itemCollection = PodioItem::filter(APP_ID, $filterParams);
$fieldID = 37325091;
foreach ($itemCollection['items'] as $item) {
// Get the field from the item
$field = $item->field($fieldID);
// Now you can print the value of that field
print $field->humanized_value;
// Or if you don't want to have the content sanitized:
print $field->values[0]['value'];
}
There is a lot of ways to skin this cat... this is probably the most straight forward
function getFirstValueByFieldId($fieldId, $Arraytosearch){
foreach($Arraytosearch["fields"] as $textitem){
if ($textitem->__attributes["field_id"] == $fieldId){
return $textitems->__attributes["values"][0]["value"];
}
}
}
to Use in your case would be
echo getFirstValueByFieldId("37325091", $Arraytosearch);
Basically it walks the elements in the fields array and returns the value in the first associated value in the values array where field_id is equal to the parameter of the function.
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?
I have an Array List that I want to output like my example below. How can I achieve it in PHP?
Array List:
array(
[0] => First,
[1] => Second,
[2] => Third,
)
Want to output like this:
array(
[First] => First,
[Second] => Second,
[Third] => Third
)
Thanks,
steamboy
You can use array_combine() and pass two copies of your original array:
$new_list = array_combine($list, $list);
print_r($new_list);
Maps the contents of the first argument as keys and the contents of the second argument as values, in their defined order.
I haven't tested it, but this should work
foreach ($array as $key => $value) {
$array[$value] = $value;
unset($array[$key]);
}
That should do it
That is redundancy at its finest. It makes little sense to have keys matching their values, and probably highlights the need for a design change, or a potential optimisation somewhere in your application. Turning this:
array(
[0] => First,
[1] => Second,
[2] => Third,
)
into this:
array(
[First] => First,
[Second] => Second,
[Third] => Third
)
effectively reduces the amount of information you are storing, since you the developer know in advance that keys should match values.