开发者

working with arrays

开发者 https://www.devze.com 2022-12-27 05:11 出处:网络
I currently do a query which goes through the records and forms an array. the print_r on query gives me this

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 [field开发者_开发知识库2] => 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消