I have an array:
$a = array('foo' => 'fooMe');
and I do:
print_r($a);
which prints:
Array ( [foo] => printme )
Is there a function, so when doing:
needed_function(' Array ( [foo] => printme )');
I will get the array array('foo' => 'fooMe'); back?
I actually wrote a function that parses a "stringed array" into an actual array. Obviously, it's somewhat hacky and whatnot, but it works on my testcase. Here's a link to a functioning prototype at http://codepad.org/idlXdij3.
I'll post the code inline too, for those people that don't feel like clicking on the link:
<?php
/**
* #author ninetwozero
*/
?>
<?php
//The array we begin with
$start_array = array('foo' => 'bar', 'bar' => 'foo', 'foobar' => 'barfoo');
//Convert the array to a string
$array_string = print_r($start_array, true);
//Get the new array
$end_array = text_to_array($array_string);
//Output the array!
print_r($end_array);
function text_to_array($str) {
//Initialize arrays
$keys = array();
$values = array();
$output = array();
//Is it an array?
if( substr($str, 0, 5) == 'Array' ) {
//Let's parse it (hopefully it won't clash)
$array_contents = substr($str, 7, -2);
$array_contents = str_replace(array('[', ']', '=>'), array('#!#', '#?#', ''), $array_contents);
$array_fields = explode("#!#", $array_contents);
//For each array-field, we need to explode on the delimiters I've set and make it look funny.
for($i = 0; $i < count($array_fields); $i++ ) {
//First run is glitched, so let's pass on that one.
if( $i != 0 ) {
$bits = explode('#?#', $array_fields[$i]);
if( $bits[0] != '' ) $output[$bits[0]] = $bits[1];
}
}
//Return the output.
return $output;
} else {
//Duh, not an array.
echo 'The given parameter is not an array.';
return null;
}
}
?>
If you want to store an array as string, use serialize [docs] and unserialize [docs].
To answer your question: No, there is no built-in function to parse the output of print_r into an array again.
No. But you can use both serialize and json_* functions.
$a = array('foo' => 'fooMe');
echo serialize($a);
$a = unserialize($input);
Or:
echo json_encode($a);
$a = json_decode($input, true);
you cannot do this with print_r,
var_export should allow something similar, but not exactly what you asked for
http://php.net/manual/en/function.var-export.php
$val = var_export($a, true);
print_r($val);
eval('$func_val='.$val.';');
There is a nice Online-Tool which does exatly what its name is:
print_r to json online converter
From a JSON Object its not far to creating an array with the json_decode function:
To get an array from this, set the second paramter to true. If you don't, you will get an object instead.
json_decode($jsondata, true);
I think my function is cool too, works with nested arrays:
function print_r_reverse($input)
{
$output = str_replace(['[', ']'], ["'", "'"], $input);
$output = preg_replace('/=> (?!Array)(.*)$/m', "=> '$1',", $output);
$output = preg_replace('/^\s+\)$/m', "),\n", $output);
$output = rtrim($output, "\n,");
return eval("return $output;");
}
NB: better not use this with user input data
Here is a print_r output parser, producing the same expression in PHP syntax. It is written as an interactive Stack Snippet, so you can use it here:
function parse(s) {
const quote = s => '"' + s.replace(/["\\]/g, '\\$&') + '"';
const compress = indent => " ".repeat(((indent.length + 4) >> 3) * 4);
return "$data = " + (s.replace(/\r\n?/g, "\n") + "\n").replace(
/(Array|\w+ (Object)) *\n *\( *\n|^( *)(?:\[(?:(0|-?[1-9]\d*)|(.*?))\] => |(\) *\n+))|(-?\d+(?:\.\d+)?(?:E[-+]\d+)?)\n|(.*(?:\n(?! *\) *$| *\[.*?\] => ).*)*)\n/gm,
(_, array, object, indent, index, key, close, number, string) =>
object ? "(object) [\n"
: array ? "[\n"
: close ? compress(indent) + "],\n"
: indent ? compress(indent) + (index ?? quote(key)) + " => "
: (number ?? quote(string)) + ",\n"
).replace(/,\n$/, ";");
}
// I/O handling
const [input, output] = document.querySelectorAll("textarea");
(input.oninput = () => output.value = parse(input.value))();
textarea { width: 23em; height: 12em }
<table><tr><th>Input print_r format</th><th>Output PHP syntax</th></tr>
<tr><td><textarea>
Array
(
[0] => example
[1] => stdClass Object
(
[a[] => 1.43E+19
["] => quote
[] =>
)
)
</textarea></td><td><textarea readonly></textarea></td></tr></table>
Remarks
Don't remove any line breaks from the original print_r output. For instance, both the opening and closing parentheses after Array must appear on separate lines.
Don't change the spacing around => (one space before, one after).
As print_r does not distinguish between null, "" or false (it produces no output for these values), nor between true and 1 (both are output as 1), this converter will never produce null, false or true.
As print_r does not distinguish between numbers and strings (9 could represent a number or a string), this converter will assume that the data type is to be numeric when such ambiguity exists.
stdClass Object is supported and translates to (object) [...] notation
MyClass Object will be treated as if it was a stdClass object.
String literals in the output are double quoted and literal double quotes and backslashes are escaped.
Quick function (without checks if you're sending good data):
function textToArray($str)
{
$output = [];
foreach (explode("\n", $str) as $line) {
if (trim($line) == "Array" or trim($line) == "(" or trim($line) == ")") {
continue;
}
preg_match("/\[(.*)\]\ \=\>\ (.*)$/i", $line, $match);
$output[$match[1]] = $match[2];
}
return $output;
}
This is the expected input:
Array
(
[test] => 6
)
This is how I interpreted the question:
function parsePrintedArray($s){
$lines = explode("\n",$s);
$a = array();
foreach ($lines as $line){
if (strpos($line,"=>") === false)
continue;
$parts = explode('=>',$line);
$a[trim($parts[0],'[] ')] = trim($parts[1]);
}
return $a;
}
Works for both objects and arrays:
$foo = array (
'foo' => 'bar',
'cat' => 'dog'
);
$s = print_r($foo,1);
$a = parsePrintedArray($s);
print_r($a);
Output:
Array
(
[foo] => bar
[cat] => dog
)
doesnt work on nested arrays, but simple and fast.
use
var_export(array('Sample array', array('Apple', 'Orange')));
Output:
array (
0 => 'Sample array',
1 =>
array (
0 => 'Apple',
1 => 'Orange',
),
)
json_encode() and json_decode() function will do it.
$asso_arr = Array([779] => 79 => [780] => 80 [782] => 82 [783] => 83);
$to_string = json_encode($asso_arr);
It will be as a json format {"779":"79","780":"80","782":"82","783":"83"}
Then we will convert it into json_decode() then it gives associative array same as original:
print_r(json_decode($to_string));
Output will be Array([779] => 79 => [780] => 80 [782] => 82 [783] => 83) in associative array format.
I have the following JSON format:
{
"S01": ["001.cbf", "002.cbf", "003.cbf", "004.cbf", "005.cbf", "006.cbf", "007.cbf", "008.cbf", "009.cbf"],
"S02": ["001.sda", "002.sda", "003.sda"],
"S03": ["001.klm", "002.klm"]
}
I try using this code:
$json = json_decode('{"S01":["001.cbf","002.cbf","003.cbf","004.cbf","005.cbf","006.cbf","007.cbf","008.cbf","009.cbf"],"S02":["001.sda","002.sda","003.sda"],"S03":["001.klm","002.klm"]}');
foreach($json as $key => $val) {
if ($key) { echo 'KEY IS: '.$key; };
if ($val) { echo 'VALUE IS: '.$value; };
echo '<br>';
}
But i got empty results...i need to get output like this:
KEY IS: S01
VALUE IS: 001.cbf
VALUE IS: 002.cbf
VALUE IS: 003.cbf
VALUE IS: 004.cbf
VALUE IS: 005.cbf
VALUE IS: 006.cbf
VALUE IS: 007.cbf
VALUE IS: 008.cbf
VALUE IS: 009.cbf
KEY IS: S02
VALUE IS: 001.sda
VALUE IS: 002.sda
VALUE IS: 003.sda
KEY IS: S03
VALUE IS: 001.klm
VALUE IS: 002.klm
This i need so that i can generate ul and li elements using value and key name...this is JSON format that is stored in mysql database and is read to php script that needs to parse the JSON in the above output so that i can create ul and li elements using output.
I try to do foreach but i got empty results? I know when i got value that i need to do explode string using explode(', ', $value) but i can't get $value and $key to be read as needed in PHP.
This solves your problem, you had to cast $json to array because it was considered as an stdClass object ;)
<?php
$json = json_decode('{"S01":["001.cbf","002.cbf","003.cbf","004.cbf","005.cbf","006.cbf","007.cbf","008.cbf","009.cbf"],"S02":["001.sda","002.sda","003.sda"],"S03":["001.klm","002.klm"]}');
foreach($json as $key => $val) {
echo "KEY IS: $key<br/>";
foreach(((array)$json)[$key] as $val2) {
echo "VALUE IS: $val2<br/>";
}
}
?>
Try It Online!
I recommend you to use the function var_dump($var) next time you run into troubles, it will help you to figure out what's wrong.
$json = '{"S01":["001.cbf","002.cbf","003.cbf","004.cbf","005.cbf","006.cbf","007.cbf","008.cbf","009.cbf"],"S02":["001.sda","002.sda","003.sda"],"S03":["001.klm","002.klm"]}';
$array = json_decode($json, true);
foreach($array as $key => $val) {
echo 'KEY IS:'.$key.'<br/>';
foreach($val as $_key => $_val) {
echo 'VALUE IS: '.$_val.'<br/>';
}
}
If you performed a var_dump($json) to observe the result you would see it looks like this...
$json = json_decode('{"S01":["001.cbf","002.cbf","003.cbf","004.cbf","005.cbf","006.cbf","007.cbf","008.cbf","009.cbf"],"S02":["001.sda","002.sda","003.sda"],"S03":["001.klm","002.klm"]}');
var_dump($json);
object(stdClass)[1]
public 'S01' =>
array (size=9)
0 => string '001.cbf' (length=7)
1 => string '002.cbf' (length=7)
2 => string '003.cbf' (length=7)
3 => string '004.cbf' (length=7)
4 => string '005.cbf' (length=7)
5 => string '006.cbf' (length=7)
6 => string '007.cbf' (length=7)
7 => string '008.cbf' (length=7)
8 => string '009.cbf' (length=7)
public 'S02' =>
array (size=3)
0 => string '001.sda' (length=7)
1 => string '002.sda' (length=7)
2 => string '003.sda' (length=7)
public 'S03' =>
array (size=2)
0 => string '001.klm' (length=7)
1 => string '002.klm' (length=7)
So you effectively have an array of arrays.
So for each "key" the associated "val" is an array that you have to loop through.
So you need to iterate through each key, then iterate through each val array.
foreach ($json as $key => $val) {
echo 'KEY IS: ' . $key;
echo '<br>';
foreach ($val as $value) {
echo 'VALUE IS: ' . $value;
echo '<br>';
}
echo '<br>';
}
The resulting output is...
KEY IS: S01
VALUE IS: 001.cbf
VALUE IS: 002.cbf
VALUE IS: 003.cbf
VALUE IS: 004.cbf
VALUE IS: 005.cbf
VALUE IS: 006.cbf
VALUE IS: 007.cbf
VALUE IS: 008.cbf
VALUE IS: 009.cbf
KEY IS: S02
VALUE IS: 001.sda
VALUE IS: 002.sda
VALUE IS: 003.sda
KEY IS: S03
VALUE IS: 001.klm
VALUE IS: 002.klmlm
VALUE IS: 002.klm
I want to push array into existing session array. I would like to use get[id] and I want to be able stack all the arrays added rather than delete them when a new array is pushed.
Bellow is my code and I am not getting the value, instead I get this error --- Array to string conversion. Thanks in advance.
**CODE
<?php
session_start();
if(empty($_SESSION['animals']))
{
$_SESSION['animals']=array();
}
// push array
array_push($_SESSION['animals'], array ( 'id' => "".$_GET['id'].""));
foreach($_SESSION['animals'] as $key=>$value)
{
// and print out the values
echo $key;
echo $value;
}
?>
With your code, this is what $_SESSION looks like:
array (size=1)
'animals' =>
array (size=1)
0 =>
array (size=1)
'id' => string 'test' (length=4)
In your code :
foreach($_SESSION['animals'] as $key=>$value)
key will contain 0 and value will contain array('id' => 'test'). Since value is an array, you cannot echo it like this.
If you want to echo all the characteristics of each animal, this code will work :
<?php
session_start();
if(empty($_SESSION['animals']))
{
$_SESSION['animals'] = array();
}
// push array
array_push($_SESSION['animals'], array ( 'id' => "".$_GET['id'].""));
// We go through each animal
foreach($_SESSION['animals'] as $key=>$animal)
{
echo 'Animal n°'.$key;
// Inside each animal, go through each attibute
foreach ($animal as $attribute => $value)
{
echo $attribute;
echo $value;
}
}
I'm trying to extract values from an array within an array. The code I have so far looks like this:
$values = $request->request->get('form');
$statusArray = array();
foreach ($values->status as $state) {
array_push($statusArray, $state);
}
The result of doing a var_dump on the $values field is this:
array (size=2)
'status' =>
array (size=2)
0 => string 'New' (length=9)
1 => string 'Old' (length=9)
'apply' => string '' (length=0)
When running the above I get an error basically saying 'status' isn't an object. Can anyone tell me how I can extract the values of the array within 'status'??
-> it's the notation to access object values, for arrays you have to use ['key']:
foreach ($values['status'] as $state) {
array_push($statusArray, $state);
}
Object example:
class Foo {
$bar = 'Bar';
}
$foo = new Foo();
echo $foo->bar // prints "bar"
I have been running around in circles over this for days ... please help.
I am trying to create a multidimensional array based on the number of files in a directory and the parsed filename ...
foreach ($files as $file) {
echo "$file[0] $file[1] <br>\n" ; #file[0]=Unix timestamp; file[1]=filename
$pn = explode('.', $file[1]);
$ndt = explode('_',array_shift($pn)) ;
foreach ($ndt as $arndt) {
$items[$arndt] = $ndt ; //this part does not work
echo "$ndt[0] $ndt[1] $ndt[2] $ndt[3] $ndt[4]" ;
}
print_r($items[$arndt]) ;
}
The output of my array is this:
Array ( [0] => OLPH [1] => Barbecue [2] => 03132013 [3] => 11am [4] => 2pm )
Note: I just have 1 file in the directory for testing purposes, but there will be more, hence the need for a multidimensional array ...
I then try to access the array in my html using this:
<h4><?php echo "$items[$arndt]. $ndt[1]" ?></h4>
.... naturally, this output does not print the results that I want .... For every file[1] I want to be able to print $arndt[] and access it using $items[][] notation.... however it just prints Array[]Array[] .... Please help ?
Thanks in advance,
Carlos
echoing/printing an array in string context just gives you Array. If you're dealing with multi-dimensional arrays, each dimension has to have its own loop to print out its contents.
e.g.
$arr1d = array('foo' => 'bar'); // 1D array
echo $arr1d; // outputs "Array"
$arr2d = array('foo' => array('bar' => 'baz')); // 2D array
echo $arr2d; // outputs 'Array';
echo $arr2d['foo']; // outputs 'Array'
echo $arr2d['foo']['bar']; // outputs 'baz'
foreach($arr2d as $key1 => $val1) {
echo $val1; // outputs 'Array';
foreach($val1 as $key2 => $val2) {
echo $val; // outputs 'Baz'
}
}