Hello!

Tell me, please, is it possible in PHP to convert an array received from a database into a string with PHP code to create an array?

For example, from the database I get:

Array ( [0] => Array ( [mark] => Toyota ) [1] => Array ( [mark] => Nissan ) [2] => Array ( [mark] => Ваз ) 

Need to convert to:

 $arr = array( array('mark' => 'Toyota'), array('mark' => 'Nissan'), array('mark' => 'Ваз'), ); 

It is necessary to once again not send a request to the database. Manually fill the array for a very long time.

  • Not very clear yet, do you want to generate PHP code? - cheops 5:09
  • @cheops Yes, I want to create a PHP code - Pavel

4 answers 4

You can begin to build on the following recursive function

 <?php $arr = array( array('mark' => 'Toyota'), array('mark' => 'Nissan'), array('mark' => 'Ваз'), ); function build_array($arr) { $tmp = array(); foreach($arr as $key => $child) { if(is_array($child)) { $tmp[] = build_array($child); } else { $tmp[] = "'$key' => '$child'"; } } return count($tmp) > 0 ? 'array('.implode(','.PHP_EOL, $tmp).')' : ''; } $result = build_array($arr); echo '<pre>'; print_r($result); echo '</pre>'; 

Script result

 array(array('mark' => 'Toyota'), array('mark' => 'Nissan'), array('mark' => 'Ваз')) 
  • the same castell it just needs to be unsolicited once again from mysql. and you reinvent the bicycle serialize functions - Naumov
  • one
    @Naumov, in the clarifying comments, the author informs about the need to generate the PHP code. Saving a serialized array to disk is far from a fact that the database will be faster, data, and often the resulting query, which is often cached in RAM. I just answered the author's question without thinking out for him the architecture of the application and the cache - the question is not for them. - cheops
  • and if you are asked how I run from utf8 to cp1251 and then convert from cp1251 back to utf8. You will also answer directly. - Naumov
  • one
    @cheops Thanks! This is what you need! - Pavel
  • @Naumov In vain you are so, cheops correctly understood the task and most importantly spent time on its effective decision. - Pavel

There is a var_export native

 $arr = array( array('mark' => 'Toyota'), array('mark' => 'Nissan'), array('mark' => 'Ваз'), ); var_export($arr); // вывести сразу echo var_export($arr, true); // или вернуть строку 

    As an option:

      $r = [ ['mark' => 'Toyota'], ['mark' => 'Nissan'], ['mark' => 'Ваз'], ]; $write_in_file = file_put_contents("cars.json", json_encode($r)); $read_from_file = json_decode(file_get_contents('cars.json'), 1); echo '<pre>'; var_dump($read_from_file); die('</pre>'); 

      use serialize to serialize the array to a string and write somewhere to the file for caching to convert again into an unserialize array