This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I have been searching for an answer to a PHP code problem. While it may sound easy to some users, I am having problem below:
I managed to retrieve data from a particular table with PHP and MySql. Unfortunately, I am unable to display result as a string rather than array.
I used print_r($loggedin_users).
Result:
Array ( [0] => Array ( [0] => Test ) [1] => Array ( [0] => Test1 ) )
I have tried using implode function to return me a string.
Result:
ArrayArray
May I know how do I get a result as below?
Desired result:
Test; Test1
Thank you in advance.
The problem is, that you have a two dimensional array. So you are trying to implode two arrays, which can't work. So you first have to implode the subArrays and then implode it again, e.g.
echo implode(";", array_map("implode", $loggedin_users));
Side note:
If you would have error reporting turned on you would have got a notice, saying:
Notice: Array to string conversion
You can use array_reduce():
echo array_reduce($array, function($carry, $item) {
if(is_null($carry)) {
return $item[0];
} else {
return $carry . "; " . $item[0];
}
});
Use foreach them use implode because you have multidimensional array.
foreach($loggedin_users as $key => $val){
$string = implode(', ', $val);
}
You have to create a recursive function here. so, no matter what array it is and no matter upto what extent that is nested. you'll always get desired result.
$a = array(
0 => array(0 => 'Test'),
1 => array(0 => 'Test1')
);
function implodeCustom($array){
$string = "";
foreach($array as $key => $value)
if(is_array($value)){
$string .= implodeCustom($value);
} else{
$string .= $value.";";
}
return $string;
}
echo rtrim(implodeCustom($a),';');
Related
This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
This is my array
Array
(
[0] => Array
(
[0] => SC1MTTCS6J1WK
)
[1] => Array
(
[0] => SC1MTTCSHJ1WK
)
)
But when I try to implode them using
$in_text = implode(",", $myArray3);
I can't get the value instead I got this:
Array,Array
Please assist thank you.
Here is the simple code, try this
$in_text = implode(',',array_map('implode',$myArray3));
echo $in_text;
Try this code,
$in_text = '';
foreach ($myArray3 as $key=>$val){
if(is_array($val)) {
$in_text .= ($in_text != '' ? ',' : ''). implode(",", $val);;
} else {
$in_text .= ($in_text != '' ? ',' : ''). $val;
}
}
echo $in_text;
PS: This will work upto two dimensional array.
You call implode on an array of array, which result the Array, Array. You can call like this,
implode(",", array_column($myArray3, 0));
This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 5 years ago.
I have an array value like below,
Array ( [0] => ["f","a","s","d"] [1] => ["d","b","a","c"] [2] => ["c"])
and also i want the array value like merged as below mentioned
Array ( [0] => ["f","a","s","d","d","b","a","c","c"])
The all key value should be merged under one new array key
In the PHP 5.6 release you could do this with a better approach.
PHP 5.6 added new functionality unpacking arrays called splat operater (…):
$arr = Array (["f","a","s","d"],["d","b","a","c"],["c"]);
$result = array_merge(...$arr);
You can pass your initial array as an argument to call_user_func_array and use array_merge:
$arr = Array (["f","a","s","d"],["d","b","a","c"],["c"]);
print_r(call_user_func_array('array_merge', $arr));
For php version which supports variadic arguments (since 5.6) it is simpler:
print_r(array_merge(...$arr));
Way 1:
$result = array_reduce($arr, 'array_merge', array());
Way 2:
$result = call_user_func_array('array_merge', $arr);
Way 3:
foreach ($arr as $key => $value) {
array_merge($result,$value);
}
After getting result you have to do :
for store as a string:
$tmp[] = implode(",",$result);
print_r($tmp);
or as array:
$tmp[] = result;
you can merge the arrays using array_merge http://php.net/manual/en/function.array-merge.php where you send in the array of arrays you have
with loop as you suggest.
$var = Array (["f","a","s","d"] ,["d","b","a","c"],["c"]) ;
$temp =[];
foreach ($var as $key => $value) {
foreach ($value as $key_1 => $value_1) {
array_push($temp, $value_1);
}
}
print_r([$temp]);
This question already has answers here:
Remove duplicates from Array
(2 answers)
Closed 9 years ago.
I have an array like this
Array
(
[0] => u1,u2
[1] => u2,u1
[2] => u4,u3
[3] => u1,u3
[4] => u1,u2
)
I want to remove similar values from the array
I want an out put like
Array
(
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
I tried to loop thru the input array, sort the value of the indexes alphabetically and then tried array_search to find the repeated values. but never really got the desired output
any help apprecated
You cannot use array_unique() alone, since this will only match exact duplicates only. As a result, you'll have to loop over and check each permutation of that value.
You can use array_unique() to begin with, and then loop over:
$myArray = array('u1,u2', 'u2,u1', 'u4,u3', 'u1,u3', 'u1,u2');
$newArr = array_unique($myArray);
$holderArr = array();
foreach($newArr as $val)
{
$parts = explode(',', $val);
$part1 = $parts[0].','.$parts[1];
$part2 = $parts[1].','.$parts[0];
if(!in_array($part1, $holderArr) && !in_array($part2, $holderArr))
{
$holderArr[] = $val;
}
}
$newArr = $holderArr;
The above code will produce the following output:
Array (
[0] => u1,u2
[1] => u4,u3
[2] => u1,u3
)
Use array_unique() PHP function:
http://php.net/manual/en/function.array-unique.php
Use the function array_unique($array)
array array_unique ( array $array [, int $sort_flags = SORT_STRING ] )
php manual
since u1,u2 !== u2,u1
$array=array('u1,u2','u2,u1','u4,u3','u1,u3','u1,u2');
foreach($array as $k=>$v)
{
$sub_arr = explode(',',$v);
asort($sub_arr);
$array[$k] = implode(',',$sub_arr);
}
$unique_array = array_unique($array);
//$unique_array = array_values($unique_array) //if you want to preserve the ordered keys
This question already has answers here:
How to remove empty values from multidimensional array in PHP?
(9 answers)
Closed 9 years ago.
I have this array:
$aryMain = array(array('hello','bye'), array('',''),array('',''));
It is formed by reading a csv file and the array('','') are the empty rows at the end of the file.
How can I remove them?
I've tried:
$aryMain = array_filter($aryMain);
But it is not working :(
Thanks a lot!
To add to Rikesh's answer:
<?php
$aryMain = array(array('hello','bye'), array('',''),array('',''));
$aryMain = array_filter(array_map('array_filter', $aryMain));
print_r($aryMain);
?>
Sticking his code into another array_filter will get rid of the entire arrays themselves.
Array
(
[0] => Array
(
[0] => hello
[1] => bye
)
)
Compared to:
$aryMain = array_map('array_filter', $aryMain);
Array
(
[0] => Array
(
[0] => hello
[1] => bye
)
[1] => Array
(
)
[2] => Array
(
)
)
Use array_map along with array_filter,
$array = array_filter(array_map('array_filter', $array));
Or just create a array_filter_recursive function
function array_filter_recursive($input)
{
foreach ($input as &$value)
{
if (is_array($value))
{
$value = array_filter_recursive($value);
}
}
return array_filter($input);
}
DEMO.
Note: that this will remove items comprising '0' (i.e. string with a numeral zero). Just pass 'strlen' as a second parameter to keep 0
Apply array_filter() on the main array and then once more on the inner elements:
$aryMain = array_filter($aryMain, function($item) {
return array_filter($item, 'strlen');
});
The inner array_filter() specifically uses strlen() to determine whether the element is empty; otherwise it would remove '0' as well.
To determine the emptiness of an array you could also use array_reduce():
array_filter($aryMain, function($item) {
return array_reduce($item, function(&$res, $item) {
return $res + strlen($item);
}, 0);
});
Whether that's more efficient is arguable, but it should save some memory :)
This question already has answers here:
Create a comma-separated string from a single column of an array of objects
(15 answers)
Closed 7 months ago.
I've got an array like this:
Array
(
[0] => Array
(
[name] => Something
)
[1] => Array
(
[name] => Something else
)
[2] => Array
(
[name] => Something else....
)
)
Is there a simple way of imploding the values into a string, like this:
echo implode(', ', $array[index]['name']) // result: Something, Something else, Something else...
without using a loop to concate the values, like this:
foreach ($array as $key => $val) {
$string .= ', ' . $val;
}
$string = substr($string, 0, -2); // Needed to cut of the last ', '
Simplest way, when you have only one item in inner arrays:
$values = array_map('array_pop', $array);
$imploded = implode(',', $values);
EDIT: It's for version before 5.5.0. If you're above that, see better answer below :)
In PHP 5 >= 5.5.0
implode(', ', array_column($array, 'name'))
You can use a common array_map() trick to "flatten" the multidimensional array then implode() the "flattened" result, but internally PHP still loops through your array when you call array_map().
function get_name($i) {
return $i['name'];
}
echo implode(', ', array_map('get_name', $array));