I currently do a query which goes through the records and forms an array.
the print_r on query gives me this
print_r($query) yields the following:
Array (
[0] => ( [field1] => COMPLETE [field2] => UNKNOWN [field3] => Test comment )
[1] => ( [field1] => COMPLETE [field2] => UNKNOWN [field3] => comment here )
[2] => ( [field1] => COMPLETE [field2] => UNKNOWN [field3] => checking )
[3] => ( [field1] => COMPLETE [field2] => UNKNOWN [field3] => testing )
[4] => ( [field1] => COMPLETE [field2] => UNKNOWN [field3] => working )
)
somehow I want to take this array and convert it back to php. So for example some thing like this
$myArray = array( ...)
then $myArray should yield the samething as the print_r($query) yeilds.
Thanks
An alternative to serialize that's closer to the print_r output would be
var_export — Outputs or returns a parsable string representation of a variable
var_export() gets structured information about the given variable. It is similar to var_dump() with one exception: the returned representation is valid PHP code.
Note that
var_export() does not handle circular references as it would be close to impossible to generate parsable PHP code for that. If you want to do something with the full representation of an array or object, use serialize().
Using var_export wouldn't allow you to parse back an actual print_r result. But tbh, I find attempting that not very feasible at all. If you have to do that, something is wrong with the code.
I may be underestimating your PHP experience here, but....
You do realize that $query is an array, right? You can simply do $myArray = $query without using print_r() for anything.
Do you need to convert it to text and back? Does it have to be stored somewhere? If so, can you use a different format (serialized or json)?
Use:
$phpcode = "\$myarray = " . var_export($query, true) . ";";
This returns a string representation of your $query array that is valid PHP code.
PS. You're not thinking of using eval() on it later, are you?
$filedata = serialize($query);
// write $filedata to a file
Then in another file:
// some other php file
// read in the filedata
$filedata = file_get_contents("file.dat");
$query = unserialize($filedata);
This is what I assume you meant by converting a string representation of an array into PHP. If you want to actually convert the output of print_r, then you will need to do some serious regex.
Related
I can't extract data from json that I got from an api.
I tried for hours, tried all kinds of formats. Read Stackoverflow threads like How do I extract data from JSON with PHP?, but I can't see what I am doing wrong.
This is the code so far:
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results, true);
// Some variations I tried:
var_dump($results->status[1]);
var_dump($results->data[1]->opening_price);
var_dump($results["data"][1]["opening_price"]);
End result: NULL NULL NULL
What am I doing wrong?
Thanks for the answers! I will upvote the working ones. Seems I got confused in the formating!
<?php
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results, true);
print_r($results['status']);
echo "</br>";
print_r($results['data']['opening_price']);
Try access your array that way.
The output is :
0000
6998000
Keep an eye for the nested arrays. You need to access their parent array first in order to get their values.
Have you read the documentation of json_decode() (or, at least, the accepted answer of the question you linked)? If you pass TRUE as the second argument to json_decode() (and there is no decent reason to not pass it) then it decodes the JSON to associative arrays and not objects.
The elements in a PHP array can be accessed using the square bracket syntax.
A simple call to print_r($results) tells its structure:
Array
(
[status] => 0000
[data] => Array
(
[opening_price] => 6998000
[closing_price] => 7270000
[min_price] => 6750000
[max_price] => 7997000
[average_price] => 7188302.5804
[units_traded] => 78484.9241002
[volume_1day] => 78484.9241002
[volume_7day] => 335611.84181738
[buy_price] => 7268000
[sell_price] => 7274000
[date] => 1510563513031
)
)
Now, accessing its items is a piece of cake:
echo($results['status']);
# 0000
echo($results['data']['opening_price']);
# 6998000
Remove true from json_decode so you will have object result like Demo
$results = json_decode($api_results);
var_dump($results->status);
var_dump($results->data->opening_price);
When you use json_decode with true the returned objects will be converted into associative arrays.
Use this code like i think work it fine..
<?php
$api_results = '{"status":"0000","data":{"opening_price":"6998000","closing_price":"7270000","min_price":"6750000","max_price":"7997000","average_price":"7188302.5804","units_traded":"78484.9241002","volume_1day":"78484.9241002","volume_7day":"335611.84181738","buy_price":"7268000","sell_price":"7274000","date":"1510563513031"}}';
$results = json_decode($api_results);
print_r($results);
var_dump($results->status);
$var = $results->data;
var_dump($var->opening_price);
?>
stdClass Object
(
[status] => 0000
[data] => stdClass Object
(
[opening_price] => 6998000
[closing_price] => 7270000
[min_price] => 6750000
[max_price] => 7997000
[average_price] => 7188302.5804
[units_traded] => 78484.9241002
[volume_1day] => 78484.9241002
[volume_7day] => 335611.84181738
[buy_price] => 7268000
[sell_price] => 7274000
[date] => 1510563513031
)
)
string(4) "0000"
string(7) "6998000"
Remove true from json_decode and try something like this:
var_dump($results->status);
var_dump($results->data->opening_price);
If you see {} it is refering to objects and [] indicates that it is an array. You're trying to show everything as if they were arrays
You have set the second parameter of json_decode() to true. that means the json will be converted to an array so you are not able to access the data using pointer -> (because it is not an object).
You may access the data like this:
var_dump($results['status'][0]);
var_dump($results['data'][0]['opening_price']);
P.S: Try var_dump($results) to see the exact data, so you know how to access each attribute.
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.
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,
),
);
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.