How to print specific json array values in php script? - php

I have a json array that looks like this:
{"server-host-01":{"API":"Good","JETS":"Good","HTTPD":"Good","DISK":"23% Used","CPU":"WARNING: Avg idle at: 98% "},"server-host-02":{"DISK":"18% Used","CPU":"Avg idle at: 99% "}}
I have a key then inside that key another array of key:values and then another key with the same setup of key:values inside.
In my php script i am assigning the json file to the variable of $files and then using json_decode to turn it into a php array (i think)
$files = (my_json_file.json);
$string = file_get_contents($file);
$json_a = json_decode($string, true);
Now i have the array in php i would like to print the main keys out and then print the key:values of the keys. They will be going into a html table but specially im looking for help printing out the values as i need them before i worry about the html part.

Viewing the JSON contents
You have a JSON encoded array which contains two arrays inside of it as below (which I obtained via this link):
array (
'server-host-01' =>
array (
'API' => 'Good',
'JETS' => 'Good',
'HTTPD' => 'Good',
'DISK' => '23% Used',
'CPU' => 'WARNING: Avg idle at: 98% ',
),
'server-host-02' =>
array (
'DISK' => '18% Used',
'CPU' => 'Avg idle at: 99% ',
),
)
If you wanted to view all values pertaining to server-host-01 you could do e.g.
var_dump($json_a['server-host-01']);
If you wanted only the CPU status you could to do e.g.
$server_host_01_CPU_Status = $json_a['server-host-01']['CPU'];
var_dump($server-host-01-CPU-Status);
Example code
Here's an example of the above in action:
<?php
$json = json_decode('{"server-host-01":{"API":"Good","JETS":"Good","HTTPD":"Good","DISK":"23% Used","CPU":"WARNING: Avg idle at: 98% "},"server-host-02":{"DISK":"18% Used","CPU":"Avg idle at: 99% "}}');
$server_host_01_CPU_Status = $json['server-host-01']['CPU'];
var_dump($server_host_01_CPU_Status);
foreach($json['server-host-02'] as $key => $value)
{
var_dump("$key = $value");
}
?>
Other notes
Your line $files = (my_json_file.json); is invalid PHP. I'm not 100% sure what you're trying to achieve but firstly:
1) my_json_file.json isn't wrapped in quotes so PHP is treating it as a constant variable rather than a string (and this throws an error too -- turn PHP server errors on to see it)
2) The unquoted string my_json_file.json is wrapped in parenthesis which doesn't even do anything in this case.
Assuming what you actually want is an array of file names to then open you'd want something like this:
$files = ['my_json_file.json'];
foreach($files as $file)
{
$contents = file_get_contents($file);
$json = json_decode($contents, true);
// foreach($json as $key => $value) { ...
}
I would highly recommend checking out this tutorial for the basics on handing JSON data in PHP.

Related

How to fetch saved array from a file & access it like an array

I have a file, in which I saved data in array format and later I want to read this data into a variable and this variable must behave like an array.
Suppose I have a file on my pc : C:/test.txt and it contains an array :
Array
(
[first_name] => John
[last_name] => Doe
[email] => johndoe#gmail.com
)
Now I am fetching this data using below method :
$myfile = fopen("C:/test.txt", "r");
$test = fread($myfile,filesize("C:/test.txt"));
Now when I print $test it shows the data like array but when I check the datatype of this variable then it shows String.
I have also converted this variable into array using type casting :
$test1 = (Array) $test;
But when tried to fetch any index from $test1 then it show Illegal string error.
So can somebody help me out.
Try this
$file = "C:/test.txt";
$document = fopen($file,'r');
$contents = fread($document, filesize($file));
fclose($document);
this will give you a array $contents
print_r($contents);
C:/test.php
<?php
return array(
'first_name' => null,
'last_name' => null,
'email' => 'new',
);
another file:
<?php
$array = inclde('C:/test.php');
Or save json in file C:/test.json
{"first_name":null,"last_name":null,"email":"new"}
and in another file:
<?php
$json = file_get_contents('C:/test.json');
$array = json_decode($json, true);
Do this:
// $myarray is the array
file_put_contents('my_file', serialize($myarray));
// Later ...
$array = unserialize(file_get_contents('my_file'));
You can guess what serialize or unserialize does. But read more in docs to learn more specifically.
#VladimirKovpak 's answer will work too, but for simple arrays. Using serialization, you can save nearly any object, and get it back.
If you need more control over serialization process, look into magic methods __sleep and __wakeup from docs.

Get arrays from a file then loop it

Try to get arrays from a file like...
data.txt
Array
(
[0] => 288
[1] => 287
[2] => 173
)
my.php
$data = file('data.txt');
foreach ($data as $id) {
echo $id." - ";
}
Why its echo all arrays back ? like data.txt
Why not echo like 288 - 287 - 173 ?
CLOSED : I using JSON now
When saving your data, get the string representation using serialize:
$str = serialize($arr);
You can then use unserialize to decode your array:
$arr = unserialize(file(data.txt));
Your method loads the data in data.txt as a string, and php will not parse it as code. Try
$data = eval(file(data.txt));
See more on eval here: PHP manual on eval
Also note that the syntax in data.txt is invalid. You want:
array(288, 287, 173);
PHP will automatically create the indexes as needed.
On a second note, this is probably not the best way to go about it. Not knowing what you aim to achieve here, but would it not be better to just have the array set in your php file?

How to deserialize this string into a PHP array of key => value pairs?

I'm calling the script at: http://phat-reaction.com/googlefonts.php?format=php
And I need to convert the results into a PHP array format like the one I'm currently hard coding:
$googleFonts = array(
"" => "None",
"Abel"=>"Abel",
"Abril+Fatface"=>"Abril Fatface",
"Aclonica"=>"Aclonica",
etc...
);
The php returned is serialized:
a:320:{
i:0;
a:3:{
s:11:"font-family";
s:32:"font-family: 'Abel', sans-serif;";
s:9:"font-name";
s:4:"Abel";
s:8:"css-name";
s:4:"Abel";
}
i:1;
a:3:{
s:11:"font-family";
s:38:"font-family: 'Abril Fatface', cursive;";
s:9:"font-name";
s:13:"Abril Fatface";
s:8:"css-name";
s:13:"Abril+Fatface";
}
etc...
How can I translate that into my array?
You can do this by unserializing the data (using unserialize()) and then iterating through it:
$fonts = array();
$contents = file_get_contents('http://phat-reaction.com/googlefonts.php?format=php');
$arr = unserialize($contents);
foreach($arr as $font)
{
$fonts[$font['css-name']] = $font['font-name'];
}
Depending on what you're using this for, it may be a good idea to cache the results so you're not fetching external data each time the script runs.
Use unserialize(): http://www.php.net/unserialize

Need PHP help assigning a piece of data from an Amazon S3 query to a variable

I'm using the AWS PHP SDK along with the code listed below to return a list of objects associated with a folder on my Amazon S3 service:
$s3 = new AmazonS3();
$response = $s3->list_objects($bucket, array(
'prefix' => 'myfolder/'
));
print_r($response->body);
I don't want to use "print_r" part.
The $response seems to be an array with a bunch of stuff in it:
Key, LastModified, ETag, Size, Owner
What would the PHP code look like that would loop through $response and assign one of the bits to a variable. For example, one piece of data in $response is "Key" that looks something like this:
[Key] => myfolder/myfile.pdf
what I need is:
myfolder/myfile.pdf
Please provide the code I would need to loop through the data within $response and assign each instance of "KEY" to a variable called: $haasfilepath.
Thanks!
It has been awhile since I've used php, but this should be work if I understand your problem.
If $response is an array with each element containing an associative array for the matching object.
$hassfilepath = Array();
foreach($response as $element){
$haasfilepath << $element[key];
}
The foreach will allow you to loop through all the objects returned in response. Within the loop you then push each [Key] into the array that is $haasfilepath. You now have a variable with an array of all key's returned.
As far as I understand, the response will be an XML file (not an array-name-value-pair) and you have to parse the XML file. Try researching xpath and similar methods in parse XMl file in php.
foreach ($response->body as $key => $haasfilepath)
{
echo 'value for key ', $key, ' is ', $haasfilepath, '<br>';
}
or, if you only need the key "key":
$haasfilepath = $response->body['key'];
echo $haasfilepath;

The way to store association array into MySQL and retrieve it back in PHP?

E.g:
PHP code:strong text
// $files would be stored into mysql db and will retrieve as original
$files = array('1' => '1,2,4,5', '5' => '4,5,7,23,56','8' => '45,23,56,67');
And the database table file's allFile[char]
'1' => '1,2,4,5', '5' => '4,5,7,23,56','8' => '45,23,56,67'
I thought I must convert the array data into string and then store into database,but implode only got the array value without key.So, should I use the foreach loop to get the key/value into string?
foreach ($files as $key => $value){
$str .= $key.'=>'.$value.','; // remove the last comma of the $str
}
and when I retrieve $str form database, I get:
$files = array($str);
So, am I do the right way ?!
Thank you very much!!
json_encode/json_decode are a popular choice here, as it means the database content is still readable without PHP. In my quick tests, storing as JSON is also more efficient.
$string = serialize($array);
$array = unserialize($string);
http://php.net/manual/ru/function.serialize.php
http://php.net/manual/ru/function.unserialize.php

Categories