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 this kind of array in my $tag variable.
Array
(
[0] => Array
(
[tag_name] => tag-1
)
[1] => Array
(
[tag_name] => tag-2
)
[2] => Array
(
[tag_name] => tag-3
)
)
What I'm trying to do is get all the tag names and implode them with a coma then make it a value for a text input field.
I've tried for and foreach loops so many different ways but with not much success. I'm using CodeIgniter if that helps.
You can use array_column followed by join or implode
Try this :
$string = join(',', array_column($array, 'tag_name'));
Explanation:
array_column returns the values from a single column from the input array
For your array, array_column($array 'tag_name') returns an array containing values of index tag_name, i.e returned array would be :
Array
(
[0] => tag-1
[1] => tag-2
[2] => tag-3
)
Joining with join or implode , you get your desired string,
//$string = "tag-1,tag-2,tag-3"
A simple and obvious solution might be:
$res = "";
for ($i = 0; $i < count($tag); $i++) {
$res .= $tag[$i]["tag_name"] . ",";
}
$res = trim($res, ","); //Removing the extra commas
echo $res;
You basically iterate through the array, and every element you iterate through, you add it's tag_name to a $res string.
Use array_column
$tag = implode(', ', array_column($array, 'tag_name'));
Using array_map:
$tag = implode(', ', array_map(function ($tag) {
return $tag['tag_name'];
}, $array));
Simple one liner !!
$array = [
[
"tag_name" => 'tag-1'
],
[
"tag_name" => 'tag-2'
],
[
"tag_name" => 'tag-3'
],
];
implode(',', array_column($array, 'tag_name'));
Related
This question already has answers here:
Return single column from a multi-dimensional array [duplicate]
(7 answers)
How to implode array indexes?
(1 answer)
Closed 3 years ago.
I have an array that I am trying to convert into two strings, one with dates and one with the data values. This is a sample array:
[$output Array below]
Array
(
[2019-03-19] => Array
(
[data_values] => 1566
)
[2019-03-18] => Array
(
[data_values] => 1542
)
[2019-03-17] => Array
(
[data_values] => 786
)
[2019-03-16] => Array
(
[data_values] => 756
)
)
A desired output would be something like:
$dates = '2019-03-19,2019-03-18,2019-03-17,2019-03-16';
$data_values = '1566,1542,786,756';
I've tried this, which will give me the data_values but I can't get the dates, I assume because its the array key?
function implode_r($g, $p) {
return is_array($p) ?
implode($g, array_map(__FUNCTION__, array_fill(0, count($p), $g), $p)) :
$p;
}
$data_values = implode_r(',', $output);
echo $data_values;
You can just use array_keys and array_column:
$dates = implode(',', array_keys($output));
$data_values = implode(',', array_column($output, 'data_values'));
Demo on 3v4l.org
This will give you the answer you expect:
<?php
// Build strings based on array
function implode_r($output) {
$dates = $data_values = "";
if(is_array($output)){
$dates=implode(',',array_keys($output));
$data_values=implode(',',array_column($output, 'data_values'));
}
return compact('dates', 'data_values');
}
// Example usage
$output = [
"2019-03-17" => ["data_values" => 1],
"2019-03-18" => ["data_values" => 2],
"2019-03-19" => ["data_values" => 3],
"2019-03-20" => ["data_values" => 4]
];
$result = implode_r($output);
echo $result['dates'];
echo $result['data_values'];
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 this return array
$leaseArray = Array ( [0] => Array ( [LeaseNumber] => OL/2011/0343 ) [1] => Array ( [LeaseNumber] => 184 ) [2] => Array ( [LeaseNumber] => OL/2011/0118 ) [3] => Array ( [LeaseNumber] => OL/2016/1759 ) [4] => Array ( [LeaseNumber] => OL/2013/0858 ) [5] => Array ( [LeaseNumber] => OL/2012/0535 ) [6] => Array ( [LeaseNumber] => OL/2017/2208 ) [7] => Array ( [LeaseNumber] => 2355 ) )
I want to save all the values of LeaseNumber in to one comma separated string
like $string = "OL/2011/0343 , 184 , OL/2011/0118 , OL/2016/1759"
please help me
$lease = array();
for($i=0;$i<=count($leaseArray); $i++){
$lease = $leaseArray[$i]['LeaseNumber'];
}
If you want a one-liner then this is the way
$csv = implode(' , ', array_column($a, 'LeaseNumber'));
As I said in the comments, 1 line, 2 function calls.
If you want a one-liner then this could work:
$csv = implode( ' , ', array_map( function( $a ){ return $a[ 'LeaseNumber' ]; }, $leaseArray ) );
expanded:
$csv = implode( ' , ', // step 2: implode on ' , ': space-comma-space
array_map( // step 1: pass $lease array into array_map so that we can get a new array
function( $a ){ return $a[ 'LeaseNumber' ]; }, // Accept each array in $a and only return the LeaseNumber. array_map will build a new array out of just these values
$leaseArray // the array to be processed
)
);
In essence, this is the same as:
$csv = implode( ' , ', array_column( $a, 'LeaseNumber' ) );
but array_map() allows you to transform the data before output/return if you need to.
One-liners are great but sometimes hard to read. If you want to stick with what you have here are some note
<?php
$array = array(array("LeaseNumber" => "OL/2011/0343"), array("LeaseNumber"=> 184 ), array("LeaseNumber"=> "OL/2011/0118") , array("LeaseNumber"=> "OL/2016/1759"), array("LeaseNumber"=> "OL/2013/0858"), array("LeaseNumber"=> "OL/2012/0535"), array("LeaseNumber"=> "OL/2017/2208"), array("LeaseNumber"=> 2355));
$lease = array();
//Not equal to the count it starts at 1 not 0
for($i=0;$i<count($array); $i++){
//lease is an array add to the index not overwrite
$lease[] = $array[$i]['LeaseNumber'];
}
//You needed to finish with this
$csv = implode(", ",$lease);
echo $csv;
As an fyi switch to a foreach in this case makes life easier:
$lease = array();
foreach($array as $obj){
$lease[] = $obj["LeaseNumber"];
}
This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I'm trying to loop through an array that I got from preg_match_all result in order to create one string from all results.
Array looks like this:
print_r($matches[0]);
Array
(
[0] => Array
(
[0] => 8147
[1] => 3
)
[1] => Array
(
[0] => 8204
[1] => 20
)
)
And my code:
$found = count($matches[0]);
for ($i = 0; $i <= $found; $i++) {
$string = $matches[0][$i];
}
I would like to get result of $string like this: 8147, 8204.
How I can append $matches[0][0] to $matches[0][1] etc. in string variable using loop?
You can do this some ting like that
$string = "";
foreach($matches[0] as $value) {
$string .= $value[0].", ";
}
$string = rtrim(", ",$string);
With php5.5 and more you can use array_column + implode:
echo implode(', ', array_column($matches, 0));
Try following code. Loop through array and get values
$arr =Array
(
0 => Array
(
0 => 8147,
1 => 3
),
1 => Array
(
0 => 8204,
1 => 20
)
);
$match_array = array();
foreach($arr as $key=>$value)
{
$match_array[] = $value[0];
}
$str = implode(",",$match_array);
echo $str;
DEMO
OR simply use array_column to get specific column as array then use implode
$arr =Array
(
0 => Array
(
0 => 8147,
1 => 3
),
1 => Array
(
0 => 8204,
1 => 20
)
);
$match_array = array_column($arr,0);
$str = implode(",",$match_array);
echo $str;
DEMO
You can use array_column, no need to loop over the array
$result = join(',', array_column($arr, 0));
This question already has answers here:
PHP array - explode some comma separated elements into new items
(8 answers)
Closed 5 months ago.
I have a array with some array values contains multiple values separated by comma as shown below.
$a = array(
'0' => 't1,t2',
'1' => 't3',
'2' => 't4,t5'
);
I need output in the following format.
Array
(
[0] => t1
[1] => t2
[2] => t3
[3] => t4
[4] => t5
)
This is how tried and getting the results. Is there any other alternative way without looping twice.
$arr_output = array();
foreach($a as $val)
{
$temp = explode(',', $val);
foreach($temp as $v)
{
$arr_output[] = $v;
}
}
Thanks.
First convert your old array in to string like,
$old_array = array
(
"t1,t2",
"t3",
"t4,t5"
);
to
$string = implode(",", $old_array);Nowecho $string; gives a string with coma separator now using this you get desired array
$new_array = explode(",", $string);
If you print this you will get
Array(
[0] => t1
[1] => t2
[2] => t3
[3] => t4
[4] => t5)
$array = Array (
"t1,t2",
"t3",
"t4,t5"
);
$splitted = array_map (function ($a) {return explode (",", $a);}, $array);
$arr = array_reduce($splitted, function ($a, $b) {
return array_merge($a, (array) $b);
}, []);
print_r ($arr);
First of all, you split every string by coma. You get an array of arrays.
To merge them, you call a merging function, such as the one in the example with array_reduce.
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 the following array:
Array
(
[id] => 1043847
[company] => Array
(
[businesstype] => Array
(
[0] => Array
(
[id] => 6
[name] => Business Service Provider
)
[1] => Array
(
[id] => 8
[name] => Retailer
)
)
)
)
I would like to be able to get the value of company -> businesstype -> name for all the arrays inside businesstype so it would display like this:
Business Type(s): Business Service Provider, Retailer
Right now if I do this:
<?php echo($chamber_member['company']['businesstype']['name']); ?>
Nothing happens, if I do this:
<?php echo($chamber_member['company']['businesstype'][0]['name']); ?>
I get only the one for array [0]. How can I get both values separated by a comma like on the example above? Any help is appreciated, thank you in advance!!
This should work for you:
First get the column into an array with array_column(), then you can simply implode() this array ,e.g.
echo implode(",", array_column($chamber_member["company"]["businesstype"], "name"));
foreach($chamber_member['company']['businesstype'] as $a)
$b[] = $a['name'];
$result = implode(", ", $b);
Take names by array_column and cobine by implode
<?php echo implode(',', array_column($chamber_member['company']['businesstype'], 'name')); ?>
Try to loop into the array position with the 'businesstype' values:
for($i = 0; $i < count($chamber_member['company']['businesstype']); $i++){
echo $chamber_member['company']['businesstype'][$i]['name'] . ', ';
}
I like array_column() but for completeness, just foreach():
foreach($chamber_member['company']['businesstype'] as $array) {
echo $array['name'];
}
Or add to an array and implode().
Another solution using array_map():-
$arr=array
(
'id' => 1043847,
'company' => array
(
'businesstype' => array
(
array
(
'id'=> 6 ,
'name' => 'Business Service Provider'
),
array
(
'id' => 8,
'name' => 'Retailer'
)
)
)
);
echo $names = implode(',',array_map( function($person) { return $person['name']; },$arr['company']['businesstype']));
Use this. best answer for this..
$result=$chamber_member['company']['businesstype'];
$last=end($result);
for($i=0;$i<count($result);$i++)
{
$b[$i] = $result[$i]['name']; echo $b[$i]; if($last!=$result[$i]['name']){ echo ","; }
}