Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implode and Explode Multi dimensional arrays [duplicate]

Are there any functions for recursively exploding and imploding multi-dimensional arrays in PHP?

like image 478
HyderA Avatar asked Oct 10 '10 10:10

HyderA


People also ask

What is the difference between implode () and explode () functions?

This symbol is known as the delimiter. Using the explode command we will create an array from a string. The explode() function breaks a string into an array, but the implode function returns a string from the elements of an array.

How do you implode a multidimensional array?

You could create a temporary array with the required values, then implode the contents. $deviceIds = array(); foreach ($multiDimArray as $item) { $deviceIds[] = $item['device_id']; } $str = implode(',', $deviceIds);

How can we get duplicate values in multidimensional array in PHP?

To merge the duplicate value in a multidimensional array in PHP, first, create an empty array that will contain the final result. Then we iterate through each element in the array and check for its duplicity by comparing it with other elements.

What would implode explode string )) do?

As the name suggests Implode/implode() method joins array elements with a string segment that works as a glue and similarly Explode/explode() method does the exact opposite i.e. given a string and a delimiter it creates an array of strings separating with the help of the delimiter.


2 Answers

You can do this by writing a recursive function:

function multi_implode($array, $glue) {     $ret = '';      foreach ($array as $item) {         if (is_array($item)) {             $ret .= multi_implode($item, $glue) . $glue;         } else {             $ret .= $item . $glue;         }     }      $ret = substr($ret, 0, 0-strlen($glue));      return $ret; } 

As for exploding, this is impossible unless you give some kind of formal structure to the string, in which case you are into the realm of serialisation, for which functions already exist: serialize, json_encode, http_build_query among others.

like image 141
lonesomeday Avatar answered Sep 17 '22 16:09

lonesomeday


I've found that var_export is good if you need a readable string representation (exploding) of the multi-dimensional array without automatically printing the value like var_dump.

http://www.php.net/manual/en/function.var-export.php

like image 34
Dave Avatar answered Sep 16 '22 16:09

Dave