This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 6 years ago.
Hi I have an array just like below
$arr = array ( [0] => Array ( [allergy] => test ),[1] => Array ( [allergy] => test1 ) );
Here from that array I just want allergy value as comma separated string like test,test1
I tried implode but it's not working
$arr = array ( [0] => Array ( [allergy] => test ),[1] => Array ( [allergy] => test1 ) );
$str = implode (", ", $arr);
echo $str;
here is my sample
//array_column will work from php version 5.5,
$arr = array ( '0' => Array ( 'allergy' => 'test' ),'1' => Array ( 'allergy' => 'test1' ) );
$str = '';
foreach($arr as $row){
$str .=$row['allergy'].',';
}
$str = trim($str,',');
echo $str;
You can use array_column() for that, and then use implode() to comma separated string.
Your code might look something like this,
$arr = array (array ('allergy' => 'test'),array ('allergy' => 'test1') );
$arr=array_column($arr,"allergy");
$str = implode (",", $arr);
echo $str;
array_column() returns the values from a single column of the input,
identified by the second parameter(column_key).
Demo: https://eval.in/620454
Related
This question already has answers here:
Convert array of single-element arrays to a one-dimensional array
(8 answers)
Closed 3 years ago.
Sorry for asking this silly question here. I am very new to PHP language.
I am trying to know how can i convert the array.
I want to convert this array to single array like.
Convert this :-
Array ( [0] => user )
Array ( [0] => user1 )
Array ( [0] => user2 )
Array ( [0] => user3 )
Array ( [0] => user8 )
Array ( [0] => user7 )
Array ( [0] => user6 )
Convert To :-
Array("user", "user1", "user2", "user3", "user4", "user5", "user6");
To "Merge" multiple arrays into one, you can use array_merge()
A good example would be:
$array_1 = array('user');
$array_2 = array('user1');
$array_3 = array('user2');
$combined_array = array_merge($array1,$array_2,$array_3);
var_dump($combined_array);
Something like this should do:
while($row = $result->fetch_array(MYSQLI_NUM)) {
$users[] = $row[0];
}
Pack or collect all arrays into a parent array.
Then you only need to pass an array as a parameter when calling array_merge.
Update: it is better to use array_column.
$arr = [];
$arr[] = array('user');
$arr[] = array('user1');
$arr[] = array('user2');
$one_dim_array = array_merge(...$arr);
//or better
$one_dim_array = array_column($arr,0);
echo "<pre>".var_export($one_dim_array, true);
Result:
array (
0 => 'user',
1 => 'user1',
2 => 'user2',
)
Try it yourself : Sandbox
Another alternative, aside from array_merge, for the case of an arbitrary number of subarrays, you could use array_reduce and build your final array:
$inArray = [['user'],['user1'],['user2'],['user3'],['user8'],['user7'],['user6']];
$inArray = array_reduce($inArray, function($arr, $elem){
$arr[] = $elem[0];
return $arr;
});
Of course, the straightforward solution would be to use array_merge:
$inArray = array_merge(...$inArray);
I have a set of values as a string, like so:
MyCustomProductID1
MyCustomProductID2
Then I proceed to create an array out of these values with explode( "\n", $myProductIdString)
Now I have additional data (strings) that I want to combine with the value from my first array. I want that simple array into a multidimensional one:
Array
(
[0] => Array
(
[id] => MyCustomProductID1
[url] => http://example.com/MyCustomProductID1.jpg
)
[1] => Array
(
[id] => MyCustomProductID2
[url] => http://example.com/MyCustomProductID2.jpg
)
)
How do I get that first array into a multidimensional one and push data along with it?
Instead of direct assigning values to array use loop-
<?php
$str = "MyCustomProductID1
MyCustomProductID2";
$arr = explode("\n", $str);
$result = [];
$url_array = ["http://example.com/MyCustomProductID1.jpg", "http://example.com/MyCustomProductID2.jpg"];
for($i=0;$i<count($arr);$i++){
$result[$i]['id'] = $arr[$i];
$result[$i]['url'] = $url_array[$i];
}
print_r($result);
?>
I'm using PHP.
I have the following array:
Array
(
[home] => 9
[pets] => 8
[dogs] => 7
[shampoo] => 7
[cover] => 6
)
I want to create a comma separated list which is:
home,pets,dogs,shampoo,cover
Here's what I'm trying but giving me blank string ($words is the array):
$myWords = implode(',',$words[0]);
Do I need to loop instead?
You're close. You just need the keys from that array. array_keys() will do that for you:
$myWords = implode(',',array_keys($words));
$string = implode(',', array_keys($words));
$words[0] does not exist in your array, because all of your keys are strings.
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:
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));