PHP dump variable as PHP code - php

I'm looking for a function to dump a multi-dimension array so that the output is valid php code.
Suppose I have the following array:
$person = array();
$person['first'] = 'Joe';
$person['last'] = 'Smith';
$person['siblings'] = array('Jane' => 'sister', 'Dan' => 'brother', 'Paul' => 'brother');
Now I want to dump the $person variable so the the dump string output, if parsed, will be valid php code that redefines the $person variable.
So doing something like:
dump_as_php($person);
Will output:
$person = array(
'first' => 'Joe',
'last' => 'Smith',
'siblings' => array(
'Jane' => 'sister',
'Dan' => 'brother',
'Paul' => 'brother'
)
);

var_export()
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.

serialize and unserialize
This is useful for storing or passing PHP values around without losing their type and structure. In contrast to var_export this will handle circular references as well in case you want to dump large objects graphs.
The output will not be PHP code though.

Related

Print result is different in the array function

I have a problem with the array PHP function, below is my first sample code:
$country = array(
"Holland" => "David",
"England" => "Holly"
);
print_r ($country);
This is the result Array ( [Holland] => David [England] => Holly )
I want to ask, is possible to make the array data become variables? For second example like below the sample code, I want to store the data in the variable $data the put inside the array.:
$data = '"Holland" => "David","England" => "Holly"';
$country = array($data);
print_r ($country);
But this result is shown me like this: Array ( [0] => "Holland" => "David","England" => "Holly" )
May I know these two conditions why the results are not the same? Actually, I want the two conditions can get the same results, which is Array ( [Holland] => David [England] => Holly ).
Hope someone can guide me on how to solve this problem. Thanks.
You can use the following Code.
<?php
$country = array(
"Holland" => "David",
"England" => "Holly"
);
foreach ($country as $index => $value)
{
$$index = $value;
}
?>
Now, Holland & England are two variables. You can use them using $Holland etc.
A syntax such as $$variable is called Variable Variable. Actually The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So there is this thing called
Destructuring
You can do it something like ["Holland" => $eolland, "England" => $england] = $country;
And now you have your array elements inside the variables.
Go read the article above if you want more information about this because it gets really useful (especially in unit tests usind data provders from my experience).
If you want to extract elements from an associative array such that the keys become variable names and values become the value of that variable you can use extract
extract($country);
To check what changed you can do
print_r(get_defined_vars());
Explanation on why the below does not work
$data = '"Holland" => "David","England" => "Holly"';
When you enclose the above in single quotes ' php would recognise it as a string. And php will parse a string as a string and not as an array.
Do note it is not enough to create a string with the same syntax as the code and expect php to parse it as code. The codes will work if you do this
$data = ["Holland" => "David","England" => "Holly"];
However, now $data itself is an array.
A simple copy of an array can be made by using
$data = $country;

Return textfile as multidimensional array

Hope everything is good.
I use php file() and it works very well. I only need to separate my "values" in the txt-file with a new row, and then 'file()' will give me the contents of the txt-file as an array with all the values separately.
I do not know if I can take the same function one step further to achieve 'key/values' and 'multidimensional arrays'. If not, what do I have for other options to be able to save 'text data' in a txt file and then get it back in a multidimensional array?
At the moment, I only get the following:
[0] => 'value1',
[1] => 'value2',
[2] => 'value3',
If you know any solutions that are very straightforward and can put me on the right track here, I am very grateful.
A simple primer for doing this with JSON:
// example array of data
$myarray = array();
$myarray[] = ['name' => 'value 1','age' => '31','city' => 'nowhere'];
$myarray[] = ['name' => 'value 2','age' => '12','city' => 'somewhere'];
$myarray[] = ['name' => 'value 3','age' => '67','city' => 'anywhere'];
print_r($myarray);
// to save your array to a file
file_put_contents('/path/to/file.json',json_encode($myarray));
// now to retrieve:
$myarray = json_decode(file_get_contents('/path/to/file.json'),true);
print_r($myarray);
By doing it this way, you retain those keys you want, and the values. The JSON encoding/decoding handles all the painful bits of storing it as text in a flatfile.

How to use json and php

I'm new to JSON, but I have experience in PHP. Can someone explain to me how JSON works, especially with PHP, and EASY way would be nice.
EX: I have a php array like:
array(
array('id' => 1, 'img' => "http.img1.png", 'title' => 'ice cream'),
array('id' => 2, 'img' => "http.img2.png", 'title' => 'silly snail'),
array('id' => 3, 'img' => "http.img3.png", 'title' => 'big bear'),
array('id' => 4, 'img' => "http.img4.png", 'title' => 'Funny cat'),
);
is this fine, or should I alter this array? I want to convert this to a JSON Object. In the php array should there be a parent, and do I have to assign array elements as children, or can each php obj be it's own JSON obj? Thank you!
Just run json_encode on the variable that you want to turn into a json string.
$something = array("test" => array("value", "another value", 4));
echo json_encode($something)
This will produce
{"test":["value","another value",4]}
Also, putting that string into $something = json_decode("{"test":["value","another value",4]}"); will produce back the same array that was passed into json_encode.
Note that JSON is not a programming language; it is a way to represent objects. http://json.org has a complete visual representation of how to use it. JSON's main components are Arrays (surrounded by []) and Objects (surrounded by {}). Arrays are lists of comma separated values (see json.org for how to tell it the types...its pretty simple) while objects are key:value pairs separated by commas between each pair where they key is a string surrounded by quotation marks. Above I created an Object with a key called "test" whose value was an Array with two strings and a number in it.
Use json_encode() for encoding the array, get the array back by using json_decode().

Problem inserting string into array

i'm trying to insert an implode generated string to an array that then later be used for json implementation
the implode generated string is look like this
'id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]
i would like to used it in this code
$this->_JsonArr[]=array($Generated string);
to achieve something like this
$this->_JsonArr[]=array('id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]);
instead i got something like this
$this->_JsonArr[]=array(" 'id' => $this->_SqlResult[0],'UserId' => $this->_SqlResult[1],'Msg' => $this->_SqlResult[2],'MsgStamp' => $this->_SqlResult[3]");
seem like generated string is treated as one element as key and value pair.
obviously i can get expected output from mysql because of this, can anybody help me with this
Why do you need to implode anything? Just pass the array:
$this->_JsonArr[] = your-non-imploded-array-here;
I think a full solution to what you want to do is something like this (i.e., the third code box in your question):
$row = array(
'id' => $this->_SqlResult[0],
'UserId' => $this->_SqlResult[1],
'Msg' => $this->_SqlResult[2],
'MsgStamp' => $this->_SqlResult[3]
);
$this->_JsonArr[] = $row;
$this->_JsonArr[]=array($Generated
string);
Looks like you want use arrays keys and values, but as I see you put into array plain string with expectation that array parse your plain string in format: keys => values.
You can try create array like below:
$this->_JsonArr[ $Generated_key ] = array( $Generated_value );
(Please correct me if I wrong understand your question).

Parsing JSON from PHP

I'm trying to iterate in a JSON object that is returned from a PHP script. The return part is something like:
$json = array("result" => -1,
"errors" => array(
"error1" => array("name" => "email","value" => "err1"),
"error2" => array("name" => "pass","value" => "err2")
)
);
$encoded = json_encode($json);
echo $encoded;
So, in JavaScript I can do:
var resp = eval('(' + transport.responseText + ')');
alert(resp.length);
alert(resp.errors.error1.name);
But I can't do:
alert(resp.errors.length);
I would like to iterate errors, that's why I'm trying to get the length. Can somebody give me a hint? Thanks!
To be able to do that, you need resp.errors to be a Javascript array, and not a Javascript object.
In PHP, arrays can have named-keys ; that is not possible in Javascript ; so, when using json_encode, the errors PHP array is "translated" to a JS object : your JSON data looks like this :
{"result":-1,"errors":{"error1":{"name":"email","value":"err1"},"error2":{"name":"pass","value":"err2"}}}
Instead, you would want it to look like this :
{"result":-1,"errors":[{"name":"email","value":"err1"},{"name":"pass","value":"err2"}]}
Notice that "errors" in an array, without named-keys.
To achieve that, your PHP code would need to be :
$json = array(
"result" => -1,
"errors" => array(
array("name" => "email","value" => "err1"),
array("name" => "pass","value" => "err2")
)
);
$encoded = json_encode($json);
echo $encoded;
(Just remove the named-keys on errors)
Have a look at your JSON output. resp.errors will be something like this:
{"error1": {"name": "email", "value": "err1"}, ...}
As you can see, it's an object, not an array (since you passed it an associative array and not an numerically indexed array.) If you want to loop through an object in JavaScript, you do it like this:
for (var error in resp.errors) {
alert(resp.errors[error].name);
}
If you want it to be a JavaScript array, your PHP should look like this:
$json = array("result" => -1, "errors" => array(
array("name" => "email","value" => "err1"),
array("name" => "email","value" => "err1")
));
If you inspect the evaluated object in Firebug, you would see that "errors" is not an array but an object(associated arrays in PHP translates to object in JS). So you need to use for-in statement to iterate through an object.
You need to check every property name with hasOwnProperty to be sure that it is something you have sent, not some prototype property.

Categories