Php build array from comma separated array values [duplicate] - php

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.

Related

Implode Multidimensional Array Keys and Values [duplicate]

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'];

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

Remove duplicates from a multi-dimensional array based on 2 values

I have an array that looks like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2"),
array("Will","Smith","4")
);
In the end I want the array to look like this
$array = array(
array("John","Smith","1"),
array("Bob","Barker","2"),
array("Will","Smith","2")
);
The array_unique with the SORT_REGULAR flag checks for all three value. I've seen some solutions on how to remove duplicates based on one value, but I need to compare the first two values for uniqueness.
Simple solution using foreach loop and array_values function:
$arr = array(
array("John","Smith","1"), array("Bob","Barker","2"),
array("Will","Smith","2"), array("Will","Smith","4")
);
$result = [];
foreach ($arr as $v) {
$k = $v[0] . $v[1]; // considering first 2 values as a unique key
if (!isset($result[$k])) $result[$k] = $v;
}
$result = array_values($result);
print_r($result);
The output:
Array
(
[0] => Array
(
[0] => John
[1] => Smith
[2] => 1
)
[1] => Array
(
[0] => Bob
[1] => Barker
[2] => 2
)
[2] => Array
(
[0] => Will
[1] => Smith
[2] => 2
)
)
Sample code with comments:
// array to store already existing values
$existsing = array();
// new array
$filtered = array();
foreach ($array as $item) {
// Unique key
$key = $item[0] . ' ' . $item[1];
// if key doesn't exists - add it and add item to $filtered
if (!isset($existsing[$key])) {
$existsing[$key] = 1;
$filtered[] = $item;
}
}
For fun. This will keep the last occurrence and eliminate the others:
$array = array_combine(array_map(function($v) { return $v[0].$v[1]; }, $array), $array);
Map the array and build a key from the first to entries of the sub array
Use the returned array as keys in the new array and original as the values
If you want to keep the first occurrence then just reverse the array before and after:
$array = array_reverse($array);
$array = array_reverse(array_combine(array_map(function($v) { return $v[0].$v[1]; },
$array), $array));

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

PHP: Better way to replace string value in array with an array?

I'm new to PHP so I'm not sure how to optimize this code.
I execute a Python script from PHP and the $output variable returned is an array of arrays.
exec (" /Users/$USER/anaconda/bin/python /Applications/MAMP/cgi-bin/Evaluation1.py",$output)
Each array within the $output array contains one string value separated by commas. So $output is Array ( [0] => 1, 好, 0 [1] => 2, 妈妈, 3), etc.
In each array within the $output array, I use explode on the string value to create an array, and add it to my new $output array called $output2
$output2 = array();
foreach($output as $value){
$myArray = explode(',', $value);
$output2[] = $myArray;
}
Is there a way to just replace/overwrite the string value in the arrays within $output with the new array, instead of adding each item to a new $output2 array?
You could use array_walk to do the loop over output. You pass in a callback function that is called for each value by reference so any changes to the passed in value stick to the array.
Test data:
$output = array(
'1,A,2',
'2,B,3',
'3,C,4'
);
PHP >= 5.3.0
array_walk($output, function(&$val){ $val = explode(',', $val); } );
Older PHP
function mySplit(&$val){
$val = explode(',', $val);
}
array_walk($output, 'mySplit');
Both output:
Array
(
[0] => Array
(
[0] => 1
[1] => A
[2] => 2
)
[1] => Array
(
[0] => 2
[1] => B
[2] => 3
)
[2] => Array
(
[0] => 3
[1] => C
[2] => 4
)
)
Some great answers already. Just adding this for completeness.
$ar = array(
"1,2,3",
"4,5,6"
);
foreach($ar as $k => $v) {
$ar[$k] = explode(',', $v);
}
Wold be interesting to see a a performance difference of the different methods although i doubt it would be much.

Categories