How can I implode() a multidimensional array into a string? - php

I have an array which has multiple arrays inside of like. Here is how it looks like:
Array (
[0] => Array (
[0] => s1
[1] => s2
[2] => s5
[3] => s1
[4] => s25
[5] => s1
[6] => s6
[7] => s6
[8] => s1
)
[2] => Array (
[0] => a2
[1] => a1
[2] => a4
)
[3] => Array ( )
[4] => Array ( )
)
What I'm trying to figure out is how I can turn these multiple arrays into 1 string where is has values from all arrays split with commas $values = "s1,s2,s5.."
I used impode() before but with this type of array, it's not functioning. Another problem in this is empty arrays which i believe can be removed with array_filter().
$destination_array = array_filter($tags_list);
$destination_array = implode(",", $tags_list);
print_r($destination_array);

You have a two dimensional array here. And neither implode() or array_filter() work with multidimensional arrays.
This means you filter all empty values out of the first dimension and also try to implode the first dimension:
Array (
[0] => Array (
[0] => s1
[1] => s2
[2] => s5
[3] => s1
[4] => s25
[5] => s1
[6] => s6
[7] => s6
[8] => s1
)
[2] => Array (
[0] => a2
[1] => a1
[2] => a4
)
[3] => Array ( )
[4] => Array ( )
↑ Filter first dimension and implode it
)
So obviously what you have to do is, you have to filter each subArray. Then implode each subArray and implode all strings together again.
How can we do this? Just use array_map().
With array_map() you go through each subArray and first filter all empty values out with array_filter(). Then you implode() each subArray to a string. After this you will end up with an array like this:
Array
(
[0] => s1,s2,s5,s1,s25,s1,s6,s6,s1
[2] => a2,a1,a4
)
And then you have to implode it again to get 1 string out of it.
Code:
echo implode(",", array_filter(array_map(function($v){
return implode(",", array_filter($v));
}, $array)));
output:
s1,s2,s5,s1,s25,s1,s6,s6,s1,a2,a1,a4

The desired result can be achieved a number of ways (beyond Rizier's function approach which is good and clean):
Demo
Method #1: the boring / loopy / fast way
$array = [
['s1','s2','s5','s1','s25','s1','s6','s6','s1'],
2 => ['a2','a1','a4'],
[],
[]
];
$result = [];
foreach ($array as $subarray) {
if ($subarray) {
$result[] = implode(',', $subarray);
}
}
echo implode(',', $result);
Method #2: the handy "leafnode" grabber
array_walk_recursive(
$array,
function($v) {
static $first;
echo $first . $v;
$first = ',';
}
);
Method #3: the slower, unorthodox regex ways:
echo implode(
',',
preg_match_all(
'/[a-z]\d+/',
json_encode($array),
$out
)
? $out[0]
: []
);
And
echo implode(
',',
preg_split(
'/\W+/',
json_encode(array_values($array)),
0,
PREG_SPLIT_NO_EMPTY
)
);
Output (from each of the above:
s1,s2,s5,s1,s25,s1,s6,s6,s1,a2,a1,a4

I think this will work:
$str='';
foreach($array as $k=>$v){
if(is_array($v)){
$str.=implode(',',$v);
}
}

Related

Remove empty string in array of strings

It seems that there are dozens of topic with similar problem, and mostly all have the same answer: use array_filter, array_map. The problem is that I used them, but it didn't quite help. So I have an array (is built from data in csv file):
Array
(
[0] => Array
(
[0] => name
[1] => title
[2] => email
)
[1] => Array
(
[0] => First
[1] => title 1
[2] => email1#ex.com
)
[2] => Array
(
[0] => second
[1] => title 1
[2] => email2#ex.com
)
[3] => Array
(
[0] =>
)
[4] => Array
(
[0] => third
[1] => title 1
[2] => email3#ex.com
)
[5] => Array
(
[0] =>
)
[6] => Array
(
[0] =>
[1] =>
[2] =>
)
)
I have to delete all empty arrays. So I use such code:
while (($row = fgetcsv($file, 8192, ';')) !== false) {
if (array(null) !== $row) { // ignore blank lines
$csv[] = $row;
}
}
$array = array_filter(array_map('array_filter', $csv));
$array now is:
Array
(
[0] => Array
(
[0] => name
[1] => title
[2] => email
)
[1] => Array
(
[0] => First
[1] => title 1
[2] => email1#ex.com
)
[2] => Array
(
[0] => second
[1] => title 1
[2] => email2#ex.com
)
[3] => Array
(
[0] => third
[1] => title 1
[2] => email3#ex.com
)
[4] => Array
(
[1] =>
)
)
Why there is a 4th array with empty value? I need to get rid of it.
gettype($array[4][1]) = string
UPDATE
The csv has empty rows, and even just a ";" delimiter without any string. I cannot influence on the process of inserting data into this csv.
The csv looks like this:
1 row: name;title;email
2 row: First;title 1;email1#ex.com
3 row: second;title 1;email2#ex.com
4 row:
5 row: third;title 1;email3#ex.com
6 row:
7 row: ; ;
and mostly all have the same answer: use array_filter, array_map.
array_filter is a good approach, but I wouldn't use array_map, but array_reduce:
$array = array_filter(
$csv,
function ($value) {
return 0 < array_reduce(
$value,
function ($carry, $item) {
return empty(trim($item)) ? $carry : $carry + 1;
},
0
);
}
);
With array_reduce, I count the non-empty elements in an array. And if there are zero non-empty elements, the array is thrown away with array_filter.
For reference, the PHP 7.4-syntax, which looks nicer in my eyes, but could be a bit confusing at first
$array = array_filter(
$csv,
fn ($val) => 0 < array_reduce(
$val,
fn ($carry, $item) => empty(trim($item)) ? $carry : $carry + 1,
0
)
);

How to split string into an associative array which has arrays within arrays

I have the following string: names=bob;mike;sam&age=30;23;22&fav-nums=200;300;400
I was wondering if there is a function which can split this into an associative array which as arrays within it. For example
Array (
["name"] => Array
(
bob,
mike,
sam
)
["age"] => Array
(
30,
23,
22
)
["fav-nums"] => Array
(
200,
300,
400
)
)
You can user parse_str() and explode() functions to achieve this.
Steps:
1) Use parse_str() function, it will split your string into associative array.
2) Now loop over it and go for key values.
3) keys will be the required keys (names, age and fav-nums) and you want values to be array.
4) explode() the values with ; and you will get required values.
Working code:
$str = "names=bob;mike;sam&age=30;23;22&fav-nums=200;300;400";
parse_str($str, $output);
$arr = [];
if (! empty($output)) {
foreach ($output as $key => $value) {
$arr[$key] = explode(';', $value);
}
}
echo '<pre>';print_r($arr);echo '</pre>';
Output:
Array
(
[names] => Array
(
[0] => bob
[1] => mike
[2] => sam
)
[age] => Array
(
[0] => 30
[1] => 23
[2] => 22
)
[fav-nums] => Array
(
[0] => 200
[1] => 300
[2] => 400
)
)
Not sure if there is a direct method of creating the sub-arrays, but parse_str() will split the initial string by & and create the starting point, then process each element with explode() (and array_walk()) to create the sub-arrays.
$start = 'names=bob;mike;sam&age=30;23;22&fav-nums=200;300;400';
parse_str($start, $output);
array_walk($output, function ( &$data ) { $data = explode(";", $data); });
print_r($output);
which gives...
Array
(
[names] => Array
(
[0] => bob
[1] => mike
[2] => sam
)
[age] => Array
(
[0] => 30
[1] => 23
[2] => 22
)
[fav-nums] => Array
(
[0] => 200
[1] => 300
[2] => 400
)
)
You can use array_map function in order to traverse the whole array as it boost up speed of your code. Also parse_str is always use in order to read Query String and convert it in array form.
$text = 'names=bob;mike;sam&age=30;23;22&fav-nums=200;300;400';
parse_str($text, $outputArray);
$array = [];
if(!empty($outputArray)) {
$array = array_map(
function($v) {
return explode(';', $v);
}, $outputArray
);
}
echo"<pre>";
print_r($array);
The result shows
Array
(
[names] => Array
(
[0] => bob
[1] => mike
[2] => sam
)
[age] => Array
(
[0] => 30
[1] => 23
[2] => 22
)
[fav-nums] => Array
(
[0] => 200
[1] => 300
[2] => 400
)
)

Delete empty value from array php

I have this array, and I need to delete the empty value and just keep the other values.
Array
(
[12] => Array
(
[0] => 12
[1] => Philippines
[2] => 94,013,200
[3] => Mid-2010
[4] => 0.0136
)
[13] => Array
(
[0] =>
[1] =>
[2] =>
[3] =>
[4] =>
)
You can use array_map and array_filter functions for removing empty values from multi-dimensional array.
Solution:
$array = array_filter(array_map('array_filter', $yourArr));
Example:
$yourArr[12] = array('12','Philippines');
$yourArr[13] = array('','');
$array = array_filter(array_map('array_filter', $yourArr));
echo "<pre>";
print_r($array);
Result:
Array
(
[12] => Array
(
[0] => 12
[1] => Philippines
)
)
Use array_map() and array_filter()
$result = array_map('array_filter', $a)
array_filter() removes blank elements from array in this case.
array_map() function calls a function on every array element, in this cause, it calls array_filter() and removes empty elements.
Working Code:
<?php
$a = array(12 => array(12, 'Philippines', '94,013,200', 'Mid-2010', '0.0136'), 13 => array('', '', '', '', ''));
$result = array_map('array_filter', $a);
echo "<pre>";
print_r($result);
echo "</pre>";
?>

Convert two or more Simple Arrays to Multidimensional Array?

Given that I have these arrays:
$array1:
Array
(
[0] => Title1
[1] => Title2
[2] => Title3
[3] => Title4
...
$array2:
Array
(
[0] => A
[1] => B
[2] => C
[3] => D
...
$array3:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
...
I want to convert all the upper arrays into one Multidimensional Array that looks like this:
Array
(
[0] => Array
(
[0] => Title1
[1] => A
[2] => 1
)
[1] => Array
(
[0] => Title2
[1] => B
[2] => 2
)
[2] => Array
(
[0] => Title3
[1] => C
[2] => 3
)
...
I have this code that does what I want but is excessive and inefficient:
$result1 = array();
foreach($array1 as $key => $value) {
$tmp = array($value);
if (isset($array2[$key])) {
$tmp[] = $array2[$key];
}
$result1[] = $tmp;
}
$result2 = array();
$i=0;
foreach($result1 as $value){
$result2[$i] = $value;
$result2[$i][] = $array3[$i];
$i++;
}
print_r($result2);
In terms of efficiency, how can I improve my code? Can this be done all in one "foreach"? What about if I have ten or even more simple arrays? If this is the case, using my code I would have to copy down the second foreach and change the variables for each other array that comes after the first two arrays.
This should work for you:
Just use array_map() to loop through all arrays at once, e.g.
$result = array_map(function($v1, $v2, $v3){
return [$v1, $v2, $v3];
}, $array1, $array2, $array3);
Or you can use call_user_func_array(), so if you expand you only have to add the variables to the array and don't have to add the arguments in the anonymous function:
$result = call_user_func_array("array_map", [NULL, $array1, $array2, $array3]);
array_map() is the way to go but it's much easier:
$result = array_map(null, $array1, $array2, $array3);

build multidimensional array from string php

EDIT: Here is a portion of $preparedstring:
555555,Jones,Brian,NYC,1000,2011-10-21 00:00:00,Check,1542,0, ,Check, ,0, ,Check, ,; 6666666,Miler,Christopher,Chicago,1000,2011-10-26 00:00:00,Check,6406,0, ,Check, ,0, ,Check, ,;
I am trying to convert a HTML table to a multidimensional array. I have converted the table into a long string, each cell being delimited with a comma and each row being delimited with a semicolon.
I am not exactly sure how to build the multidimensional array from this string. This is what I have tried so far:
<?php
$outerARR = explode(";", $preparedstring);
$arr = array
(
foreach ($outerARR as $arrvalue) {
$innerarr = explode(",", $arrvalue);
$innerarr[0]=>array
(
$innerarr[];
)
}
);
?>
this gives me a syntax error near the
$arr = array
(
opening parenthesis.
Your approach to solving the problem is sadly very wrong, though there are many solutions to your problem, I would use something like the below.
How does the code work?
First we use explode to split our string up in smaller chunks, ; is our delimiter.
We pass this newly created array to array_map as it's second parameter.
array_map takes two parameters, the first one is a function that will be called for every member of the second paramater (which should be an array).
Inside our callback to array_map we use explode to once again split out the values, now with , as our delimiter.
$data = "1,2,3;4,5,6;7,8,9";
$ret = array_map (
function ($_) {return explode (',', $_);},
explode (';', $data)
);
print_r ($ret);
output
Array
(
[0] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[1] => Array
(
[0] => 4
[1] => 5
[2] => 6
)
[2] => Array
(
[0] => 7
[1] => 8
[2] => 9
)
)
It doesn't work, why?
Probably because you are using a version of PHP prior to 5.3, if so you can use this snippet instead:
function explode_by_comma ($_) {
return explode (',', $_);
}
$ret = array_map ('explode_by_comma', explode (';', $data));
<?php
//explode first dimension of the array to create an array of rows
$outerARR = explode(";", $preparedstring);
$arr = array();
//iterate through the newly created array
foreach ($outerARR as $arrvalue) {
//explode this row into columns
$innerarr = explode(",", $arrvalue);
//add the newly created array of columns to the output array as a new index
$arr[] = $innerarr;
}
?>
You're close, but arrays don't work that way. You can't put a foreach inside an array constructor like that. It should look like this:
$outerARR = explode(";", $preparedstring);
$arr = array();
foreach ($outerARR as $arrvalue){
$innerarr = explode(",", $arrvalue);
$arr[] = $innerarr;
}
Demo: http://codepad.org/I5wFFczR
$outerARR = explode(";", $preparedstring);
$a = array();
$y=0;
foreach ($outerARR as $arrvalue){
$x=0;
$innerarr = explode(",", $arrvalue);
foreach($innerarr as $v){
$a[$y][$x++] = $v;
}
$y++;
}
print_r($a);
Array
(
[0] => Array
(
[0] => 555555
[1] => Jones
[2] => Brian
[3] => NYC
[4] => 1000
[5] => 2011-10-21 00:00:00
[6] => Check
[7] => 1542
[8] => 0
[9] =>
[10] => Check
[11] =>
[12] => 0
[13] =>
[14] => Check
[15] =>
[16] =>
)
[1] => Array
(
[0] => 6666666
[1] => Miler
[2] => Christopher
[3] => Chicago
[4] => 1000
[5] => 2011-10-26 00:00:00
[6] => Check
[7] => 6406
[8] => 0
[9] =>
[10] => Check
[11] =>
[12] => 0
[13] =>
[14] => Check
[15] =>
[16] =>
)
)

Categories