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

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

Related

JSON Database update loosing key values

I got this in my DB (23 is my picture ID):
{"23" : {"13x18":"5","20X30":"5","30x45":"4","digital":"4"}}
I want to add another data just like this one in the same spot so it would look like this :
["23" : {"13x18":"5","20X30":"5","30x45":"4","digital":"4"},
"42" : {"13x18":"2","20X30":"1","30x45":"3","digital":"1"}]
Here is the code is use :
$clientChoice = [];
$clientChoice[$post['picId']] = $test;
$select = (new GalleryCategoriesModel)->findByUrl($post['url']);
if($select['clientChoice'] != null){
$tabs = json_decode($select['clientChoice'], true);
$new = array_merge($tabs, $clientChoice);
$chosen = json_encode($new);
} else {
$chosen = json_encode($clientChoice);
}
$update = (new GalleryCategoriesModel)->update(['clientChoice'=>$chosen], $post['id']);
And here is the result i got with it :
[{"13x18":"5","20X30":"5","30x45":"4","digital":"4"},
{"13x18":"2","20X30":"1","30x45":"3","digital":"1"}]
What am I missing or doing wrong?
----------------- CORRECTION ------------------
Thanks to the answer given, here is what i do now :
$clientChoice = [];
$clientChoice[$post['picId']] = $test;
$select = (new GalleryCategoriesModel)->findByUrl($post['url']);
if($select['clientChoice'] != null){
$tabs = json_decode($select['clientChoice'], true);
$new = $tabs + $clientChoice;
$chosen = json_encode($new);
} else {
$chosen = json_encode($clientChoice);
}
$update = (new GalleryCategoriesModel)->update(['clientChoice'=>$chosen], $post['id']);
And here is what I got in my DB :
{"25":{"13x18":"1","20X30":"3","30x45":"5","digital":"1"},
"37":{"13x18":"4","20X30":"8","30x45":"3","digital":"2"}}
Your issue is with your call to array_merge. From the manual:
Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in the result array
So your two arrays that have keys of 23 and 42 end up merged as:
Array
(
[0] => Array
(
[13x18] => 5
[20X30] => 5
[30x45] => 4
[digital] => 4
)
[1] => Array
(
[13x18] => 2
[20X30] => 1
[30x45] => 3
[digital] => 1
)
)
You can work around this by using the array union operator (+), which will preserve the keys from both arrays (although it will ignore $clientChoice if the key is the same as one already existing in $tabs), however since they are id values I assume this should not occur.
$new = $tabs + $clientChoice;
In this case, $new contains:
Array
(
[23] => Array
(
[13x18] => 5
[20X30] => 5
[30x45] => 4
[digital] => 4
)
[42] => Array
(
[13x18] => 2
[20X30] => 1
[30x45] => 3
[digital] => 1
)
)
Demo on 3v4l.org

how to show comma separated values using codeigniter [duplicate]

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;

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

How can I build a dynamic array from a string in PHP?

I'm trying to create an array in PHP that has the structure defined by a string. It will loop through and use the first value as the value and the second value as the quantity. For instance the 1|3 will have the value of 1, 3 times and then loop to the next in the string.
Here is what I have so far -
<?php
$quantity = 10;
$string = '1|3,2|3';
$overall_types = array( );
$types = explode( ',', $string );
for ( $i = 1; $i <= $quantity; $i++ )
{
$qc = explode( '|', $types[0] );
$overall_types[$i] = $qc[0];
}
echo '<pre>';
print_r ( $overall_types );
echo '</pre>';
and that gets me
Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 1
[5] => 1
[6] => 1
[7] => 1
[8] => 1
[9] => 1
[10] => 1
)
but, I want the result to be
Array
(
[1] => 1
[2] => 1
[3] => 1
[4] => 2
[5] => 2
[6] => 2
[7] => 1
[8] => 1
[9] => 1
[10] => 2
)
I'm not sure how to easily switch between the exploded values.
Thanks.
You're not using the repetition count at all from what I see. Achieving this using a straight-forward approach is tricky and probably not necessary when there's a simpler way to do this.
<?php
function buildReps($string) {
$array = [];
$overall_types = array( );
$types = explode( ',', $string );
foreach ($types as $type) {
$qc = explode( '|', $type );
$array = array_merge($array, array_fill(0, $qc[1], $qc[0]));
}
return $array;
}
function buildAllReps($string, $quantity) {
$array = [];
while (count($array) < $quantity) {
$array = array_merge($array, buildReps($string));
}
return array_slice($array, 0, $quantity);
}
$quantity = 10;
$string = '1|3,2|3';
echo '<pre>';
print_r ( buildAllReps($string, $quantity) );
echo '</pre>';
The first function builds the array once based on the $string defintion. The second one just merges the results from the first one until you reach quantity and then stops and returns the correct quantity of items back.
The above outputs:
Array
(
[0] => 1
[1] => 1
[2] => 1
[3] => 2
[4] => 2
[5] => 2
[6] => 1
[7] => 1
[8] => 1
[9] => 2
)
Example in https://eval.in/629556
Beware of infinite loops which may occur if the definition supplied by $string does not produce a non-empty array.
There's a better way to do string to array in PHP.
You can use either serialize and unserialize or json_encode and json_decode to create strings and then to convert them to array. This is far better than what you would want to implement, because those methods are in the php core, which means they are faster.
http://php.net/serialize
http://php.net/manual/ro/function.json-encode.php
From json string to array, you will need to do something like this:
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
// extra boolean parameter set to true to return array instead of json object
$array = json_decode($json, true);
<?php
$quantity = 10;
$string = '1|3,2|3';
$overall_types = [];
$types = explode( ',', $string );
for($c = 0; $c < $quantity; $c++) {
foreach ($types as $currentType) {
$qc = explode( '|', $currentType );
for ($i = 0; $i < $qc[1]; $i++) {
$overall_types[] = $qc[0];
}
}
}
$overall_types = array_slice($overall_types,0,$quantity);
echo '<pre>';
print_r ( $overall_types );
echo '</pre>';
This should give you the output that you need.
Not going into micro benchmarking here but you could probably also preg_replace /g the \w|\d+, multipliers by their full string representation and only preg_split the entire string into an array after this step. Like so:
$string = '1|3,2|3';
print_r(str_split(preg_replace_callback('/(\w)\|(\d+),?/', function($a) {
return str_repeat($a[1], $a[2]);
}, $string)));
Less array handling and potentially faster.
I would however suggest to reconsider the initial string representation and look for a better approach. Why is this format needed if it needs to be converted anyway?

Simplify a multidimensional array to a 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 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'));

Categories