PHP convert array to resource

For visual presentation, for simplicity and, of course, to convey my curiosity, I am wondering how to convert a PHP array into a valid PHP resource.

See the example below: enter image description here (example image created using the dBug component, available at http://dbug.ospinto.com/ )

I made 3 examples:

  • resource: this is a typical representation of a MySQL resource displayed as a grid
  • object: create object manually from an array
  • array: handmade multidimensional array

As you can see, the resource is visual beauty, and the object and the array are created using multidimensional arrays using weak indices of numeric arrays to combine them: (

What I'm looking for will probably be something like this:

$resource_var = (resource) $array_var; 
+6
source share
4 answers

What I'm looking for is perhaps something like this:

 $resource_var = (resource) $array(var) 

You will never find it. A resource is an internal data type in PHP. If (and only if) you write yourself a PHP extension and load it, you can do the following:

 $resource = array_resource_create($array); 

Then your PHP extension would create this resource (since the mysql extension, for example, creates its specific resource type) inside this array_resource_create function. However, this would be useless, because there is still no other function that could handle this resource.

+9
source

You cannot create a resource. but you can use your own.

Try using curl, for example.

 function makeResourceFromArray($array) { $resource = curl_init(); curl_setopt($resource, CURLOPT_PRIVATE, serialize($array)); return $resource; } function makeArrayFromResource($resource) { return unserialize(curl_getinfo($resource, CURLINFO_PRIVATE)); } $resource = makeResourceFromArray(['name' => 'test']); $array = makeArrayFromResource($resource); 
+2
source

The result you show has nothing to do with the fact that it is a resource as such, but the nice print function that you use, noting that the variable you specify indicates a set of database results and a selection and display of results.

What PHP means with resource is that the variable does not actually store data in PHP, but is a pointer or link that some lower-level code module can use - in this case, the database library that can use this link to get the results of a completed query.

If you want a cute print to look similar to an array with a structure similar to a DB database, then you just need to change the cute print function to do this - you don't need to do anything with the array.

+1
source

A resource is a special type. And the resource is specific to a source that is external. Therefore, going back would be impossible.

Theoretically, an interface with a resource instance will help control the type, but this is just a meaningless theoretical conversation that is not possible in PHP.
0
source

Source: https://habr.com/ru/post/923674/


All Articles