Hardcode array for reuse in php file? - php

I don't know if this is even called "hardcoding", but I would like to build an array (for example from a mysqli_fetch_assoc query) and output it for reuse in a config.php file.
So this output from mysql would be:
[structure] => Array
(
[0] => Array
(
[structureid] => 23
[active] => 1
)
[1] => Array
(
[structureid] => 25
[active] => 1
)
And it would be stored like this in a config.php file:
$structure[0]['structureid'] = 23;
$structure[0]['active'] = 1;
$structure[1]['structureid'] = 25;
$structure[1]['active'] = 1;
Is there an easy and quick way to accomplish this?
As someone has pointed out, I could resolve this with using a json file - which I'm already doing - but I wanted to check if there would be another (quick) way of doing it as described above.

You can use var_export(), to create a readable (and in-code-reusable) array, that you can then put in a config file:
$reusableCode = var_export($yourArray, true);
Or to just output it:
var_export($yourArray);
You can put that in a config file with an return, like this:
return array(
'your' => 'values'
);
and then require it from your code:
$configData = require('yourConfigFileWithTheArray.php');

I Initially misread your question,
So you want to store mysql resource to a file?
You mentionned that you are using JSON is to solve this.
This is a good way to do it, the other way would be to serialize/deserialize the object than save them to a file. JSON solution is simple human readable.
Example:
$data = serialize($rows);
file_put_contents('data.txt', $data);
$data = file_get_contents('data.txt');
$rows = unserialize($data);
But you won't be able to read the output of the serialization.

Related

How to print specific json array values in php script?

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.

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.

Php array_rand() printing variable name

I have an array that is filled with different sayings and am trying to output a random one of the sayings. My program prints out the random saying, but sometimes it prints out the variable name that is assigned to the saying instead of the actual saying and I am not sure why.
$foo=Array('saying1', 'saying2', 'saying3');
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
echo $foo[array_rand($foo)];
So for example it will print World as it should, but other times it will print saying2. Not sure what I am doing wrong.
Drop the values at the start. Change the first line to just:
$foo = array();
What you did was put values 'saying1' and such in the array. You don't want those values in there. You can also drop the index values with:
$foo[] = 'Hello.';
$foo[] = 'World.';
That simplifies your work.
You declared your array in the wrong way on the first line.
If you want to use your array as an associative Array:
$foo=Array('saying1' => array (), 'saying2' => array(), 'saying3' => array());
Or you can go for the not associative style given by Kainaw.
Edit: Calling this on the not associative array:
echo("<pre>"); print_r($foo); echo("</pre>");
Has as output:
Array
(
[0] => saying1
[1] => saying2
[2] => saying3
[saying1] => Hello.
[saying2] => World.
[saying3] => Goodbye.
)
Building on what #Answers_Seeker has said, to get your code to work the way you expect it, you'd have to re-declare and initialise your array using one of the methods below:
$foo=array('saying1'=>'Hello.', 'saying2'=>'World.', 'saying3'=>'Goodbye.');
OR this:
$foo=array();
$foo['saying1'] = "Hello.";
$foo['saying2'] = "World.";
$foo['saying3'] = "Goodbye.";
Then, to print the contents randomly:
echo $foo[array_rand($foo)];

Serialised Array not working

I am trying to take an array of filenames and output the following...
a:1:{s:4:"docs";a:4:{i:0;a:1:{s:15:"property_imgurl";s:63:"http://wwww.example.com/image1.jpg";}i:1;a:1:{s:15:"property_imgurl";s:63:"http://wwww.example.com/image2.jpg";}i:2;a:1:{s:15:"property_imgurl";s:63:"http://wwww.example.com/image3.jpg";}i:3;a:1:{s:15:"property_imgurl";s:63:"http://wwww.example.com/image4.jpg";}}}
This is what I have so far...
<?php
$serialized_data = serialize(array('http://www.example.com/image1.jpg', 'http://www.example.com/image2.jpg', 'http://www.example.com/image3.jpg', 'http://www.example.com/image4.jpg'));
echo $serialized_data . '<br>';
?>
But this is giving me...
a:4:{i:0;s:34:"http://www.example.com/image1.jpg";i:1;s:34:"http://www.example.com/image2.jpg";i:2;s:34:"http://www.example.com/image3.jpg";i:3;s:34:"http://www.example.com/image4.jpg";}
Where am I going wrong?
There is nothing wrong with the serialized array. You're just not creating the array like you want it to be. PHP can't guess how you really want your array to be, so you have to tell PHP how you want it to be. So what you need to do is to change the input array correctly.
You're giving
array('http://www.example.com/image1.jpg', 'http://www.example.com/image2.jpg', 'http://www.example.com/image3.jpg', 'http://www.example.com/image4.jpg')
and that's completely different from the serialized array how it should be. Your Array needs to look like this
array('docs' => array(array('property_imgurl' => 'http://www.example.com/image1.jpg'), array('property_imgurl' => 'http://www.example.com/image2.jpg'), array('property_imgurl' => 'http://www.example.com/image3.jpg'), array('property_imgurl' => 'http://www.example.com/image4.jpg')))
Look at this eval
You're just missing the array key definitions.
$serialized = array(array('docs' => array(array('property_imgurl' => 'http://www.example.com/image4.jpg'))));
As you can see, each URL has a key of property_imgurl and each of those array is part of a parent array with a key of docs
Here's the eval.in

Putting file in array Php?

I have a file that has some values inside, an ordinary txt file, but I have made it look like an array
tekstovi.php
That looks like this
'1' => 'First',
'2' => 'Second',
'3' => 'Third',
Or someone have a better solution for file look :)
From that file I want to make a new array $promenjive in scope, so what is the best way to make an array from a file in php? It is easy to make explode in an ordinary array, but I don't know how to put all that in a multidimensional array :)
why don't you just make a .php file which will return an array, something like:
// somefile.php
return array(
'key1' => 'value1',
'key2' => 'value2'
);
and when you need it:
$something = require('/path/to/somefile.php');
echo $something['key1'];
Or someone have a better soluton for [the] file [format]
Create an INI file and use parse_ini_file().
If it's just an array only read by PHP, simply use include/require.
Have the file store the values in some sort of data-storing file type, e.g. xml, json, csv
PHP numerous ways of parsing and retrieving that data meaningfully. My recommendation is to use json, so with your example above it would be:
{"1":"First","2":"Second","3":"Third"}
And the corresponding PHP method to decode it:
json_decode($contents, true)
Check out the http://php.net/manual/en/function.json-decode.php for the method's full documentation, note that I set the 2nd optional argument to true since you're parsing an associative array, otherwise it will convert the data into an Object
Use JSON:
{
"foo" : "bar",
"baz" : [2, 3, 5, 7, 11]
}
PHP:
$content = file_get_contents('path/to/file');
$array = json_decode($content, true);
Et voila'.
parse_ini_file is a good solution with for a 1 or 2 dimensional array but if you need a more deeply nested structure you can use json.
$config = json_decode(file_get_contents($configFile)); // return an object, add true as a second parameter for an array instead
with the file looking something like
{
"1":"First",
"2":"Second",
"3":"Third"
}
if JSON formatting is not palatable for you then YAML or XML might be an option.
You don't need to do much, you can just create a variable in one file, and after including it will be available in the other.
file1.php:
$x = 5;
file2.php:
include file1.php
echo $x; //echoes 5

Categories