how to show comma separated values using codeigniter [duplicate] - php

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 am using codeigniter geting comma separated values but not working fine. i am sharing all code like first output foreach after gating result not show comma separated values than second show array print value aftra need output comma separated values like SLR,ACCN
Model code here
public function display_coach_name($coachID='')
{
$db2 = $this->load->database('rail',TRUE);
$ids = explode(',',$coachID);
$db2->select('coach_name');
$db2->from('mcc_coach');
$db2->where_in('id',$ids);
$query = $db2->get();
//echo $db2->last_query(); die;
if ($query->num_rows() > 0):
return $query->result_array();
else:
return 0;
endif;
}
output
<?php foreach ($coachname as $val){ echo $pizza = $val['coach_name']; }?>
//---------------------foreach-----------------output---
SLRACCN
array print
$coachname = $this->rail_ceil_model->display_coach_name($coachID);
echo"<pre>";
print_r($coachname);
//---------------------output----------------------
Array
(
[0] => Array
(
[coach_name] => GS
)
[1] => Array
(
[coach_name] => SLR
)
)
Array
(
[0] => Array
(
[coach_name] => GS
)
[1] => Array
(
[coach_name] => SLR
)
)
Array
(
[0] => Array
(
[coach_name] => GS
)
[1] => Array
(
[coach_name] => SLR
)
)
Array
(
[0] => Array
(
[coach_name] => GS
)
[1] => Array
(
[coach_name] => SLR
)
)
I have need output
SLR,ACCN

You can use implode function for converting array into comma separated values
$coachname = $this->rail_ceil_model->display_coach_name($coachID);
foreach($coachname as $val){
if(is_array($val)){
$list .= $val['coach_name'].',';
}}
print_r(substr ( $list , 0 , strlen($list) -1 ));
or
$coachname = $this->rail_ceil_model->display_coach_name($coachID);
print_r(implode(', ', array_map('coach_name', $coachname)));
or
echo implode(', ', array_column($coachname, 'coach_name'));

You may use implode function for getting comma separated values.
<?php
$coachname = array("ACCN", "SLR", "CN");
$new = implode(',',$coachname);
echo $new;
?>
Output will be:
ACCN,SLR,CN
Edit your code accordingly.

Please use array_map function then use implode function
$coachname_separated = array_map (function($value){
return $value['coach_name'];
} , $coachname);
$List = implode(', ', $coachname_separated);
echo $List;

Related

Store array of arrays value in one comma separated string [duplicate]

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"];
}

php combines array values in main array

I have total 3 array
First array contains list of titles
Second array contains list of description
third array contains images
I have already combine 1st and 2nd array as a key of first array and value of second array and I also combine 1st and 3rd array as key of 1st and value of 3rd.
Following is my arrays
1 )
Array
(
[First] => FFFFFFFFFFFFFFFF
[Second] => ssss
[0] => Array
(
[First] => eae2d7b3f20250def1892bae1abaf07f.png
[Second] => ea7ca514d1ef580f85fb42c7cb425462.png
)
)
I want output like
Array
(
[First] => FFFFFFFFFFFFFFFF
[Second] => ssss
[First] => eae2d7b3f20250def1892bae1abaf07f.png
[Second] => ea7ca514d1ef580f85fb42c7cb425462.png
)
Code
foreach ($images as $key => $value) {
$values['image']= $value;
}
$data = array_combine($_POST['title'], $images);
$mainArray = array_combine($_POST['title'], $_POST['Description']);
array_push($mainArray,$data);
echo '<pre>';
print_r($mainArray);
How can I do this?
The code below should produce the format the array as required above, although it is not the most elegant way to flatten an array. It may be worthwhile looking at previous questions like How to Flatten a Multidimensional Array?
$newArr = array();
foreach ( $mainArray as $key => $val ) {
if ( is_array( $val ) ) {
foreach ( $val as $key2 => $val2 ) {
$newArr[$key2] = $val2;
}
} else {
$newArr[$key] = $val;
}
}

How to join a column of values with comma then space? [duplicate]

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));

Obtaining all values in php array [duplicate]

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 ","; }
}

Specifying object in PHP Array from JSON

I'm trying to use a specific object type from a JSON feed, and am having a hard time specifying it. Using the code below I grab and print the specific array (max) I want,
$jsonurl = "LINK";
$json = file_get_contents($jsonurl,0,null,null);
$json_output = json_decode($json,true);
$max_output = $json_output["max"];
echo '<pre>';
print_r($max_output);
echo '</pre>';
And from the Array below, all I want to work with is the [1] objects in each array. How can I specify and get just those values?
Array
(
[0] => Array
(
[0] => 1309924800000
[1] => 28877
)
[1] => Array
(
[0] => 1310011200000
[1] => 29807
)
[2] => Array
(
[0] => 1310097600000
[1] => 33345
)
[3] => Array
(
[0] => 1310184000000
[1] => 33345
)
[4] => Array
(
[0] => 1310270400000
[1] => 33345
)
[5] => Array
(
[0] => 1310356800000
[1] => 40703
)
Well you could fetch those values with array_map:
$max_output = array_map(function($val) { return $val[1]; }, $json_output["max"]);
This requires PHP 5.3, if you use an earlier version, then you can use create_function to achieve similar results:
$max_output = array_map(create_function('$val', 'return $val[1];'), $json_output["max"]);
When you need to create new array which will contain only second values, you may use either foreach loop which will create it or use array_map() (just for fun with anonymous function available since php 5.3.0):
$newArray = array_map( function( $item){
return $item[1]
},$array);
Then you want to use last ("max" -> considering array with numeric keys) item, you can use end():
return end( $item);
And when you can process your data sequentially (eg. it's not part of some big getData() function) you can rather use foreach:
foreach( $items as $key => $val){
echo $val[1] . " is my number\n";
}
After you get $max_output...
for( $i = 0; $i < length( $max_output ); $i++ ) {
$max_output[$i] = $max_output[$i][1];
}
try this:
$ones = array();
foreach ($max_output as $r)
$ones[] = $r[1];

Categories