Convert array to comma separated values - php

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.

Related

How to extract the keys of an Array and push them to a String array?

Everyone else usually asking how to convert string array with commas to an array of key value pairs.
But my question is opposite. I want to extract the keys of the array and place them in a separate array using PHP
I have an array of this form:
Array
(
[Lights] => 4
[Tool Kit] => 4
[Steering Wheel] => 4
[Side Mirrors] => 3.5
)
and I want output to be in this form:
{"Lights", "Tool Kit", "Steering Wheel", "Side Mirrors" }
Using array_keys :
array_keys — Return all the keys or a subset of the keys of an array
So you can just extract each keys simply by using this method
$keys = array_keys($array);
Otherwise, you can loop through each values and only get the keys :
$keyArray=array_keys($array);
$keyArray=[];
foreach($array as $key => $value){
$keyArray[]=$key;
}
Use array_keys. It will return array keys as array values
$array=array('Lights' => 4,
'Tool Kit' => 4,
'Steering Wheel' => 4,
'Side Mirrors' => 3.5);
$key_array=array_keys($array);
print_r($key_array);
It will result
Array ( [0] => Lights [1] => Tool Kit [2] => Steering Wheel [3] => Side Mirrors )
Looks like you are expecting JSON output. You can just use json_encode function in a pair with array_keys.
$result = json_encode(array_keys($array));
However, your result will be ["Lights","Tool Kit","Steering Wheel","Side Mirrors"]

array to comma separated string for selected key [duplicate]

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

PHP is possible to implode ignoring specific array?

I have an array that looks like this:
Array
(
[0] => 41
[1] => 43
[2] => 44
[comment] =>
)
is there any way to implode this array ignoring ['comment']??
Now ['comment']doesn't has content but sometimes it can have content. I need to ignore ['comment'] always.
Also ['comment'] will be always the last array.
Simply use unset and implode
unset($arr['comment']);
echo implode(',',$arr);
Demo
Use a negative offset with array_splice to remove the last element of the array.
$string = implode(',', array_splice($array, -1));

PHP from string to multiple arrays at the hand of placeholders

Good day,
I have an I think rather odd question and I also do not really know how to ask this question.
I want to create a string variable that looks like this:
[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]
This should be processed and look like:
$variable = array(
'car' => array(
'Ford',
'Dodge',
'Chevrolet',
'Corvette'
),
'motorcycle' => array(
'Yamaha',
'Ducati',
'Gilera',
'Kawasaki'
)
);
Does anyone know how to do this?
And what is it called what I am trying to do?
I want to explode the string into the two arrays. If it is a sub array
or two individual arrays. I do not care. I can always combine the
latter if I wish so.
But from the above mentioned string to two arrays. That is what I
want.
Solution by Dlporter98
<?php
///######## GET THE STRING FILE OR DIRECT INPUT
// $str = file_get_contents('file.txt');
$str = '[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]';
$str = explode(PHP_EOL, $str);
$finalArray = [];
foreach($str as $item){
//Use preg_match to capture the pieces of the string we want using a regular expression.
//The first capture will grab the text of the tag itself.
//The second capture will grab the text between the opening and closing tag.
//The resulting captures are placed into the matches array.
preg_match("/\[(.*?)\](.*?)\[/", $item, $matches);
//Build the final array structure.
$finalArray[$matches[1]][] = $matches[2];
}
print_r($finalArray);
?>
This gives me the following array:
Array
(
[car] => Array
(
[0] => Ford
[1] => Dodge
[2] => Chevrolet
[3] => Corvette
)
[motorcycle] => Array
(
[0] => Yamaha
[1] => Ducati
[2] => Gilera
[3] => Kawasaki
)
)
The small change I had to make was:
Change
$finalArray[$matches[1]] = $matches[2]
To:
$finalArray[$matches[1]][] = $matches[2];
Thanks a million!!
There are many ways to convert the information in this string to an associative array.
split the string on the new line into an array using the explode function:
$str = "[car]Ford[/car]
[car]Dodge[/car]
[car]Chevrolet[/car]
[car]Corvette[/car]
[motorcycle]Yamaha[/motorcycle]
[motorcycle]Ducati[/motorcycle]
[motorcycle]Gilera[/motorcycle]
[motorcycle]Kawasaki[/motorcycle]";
$items = explode(PHP_EOL, $str);
At this point each delimited item is now an array entry.
Array
(
[0] => [car]Ford[/car]
[1] => [car]Dodge[/car]
[2] => [car]Chevrolet[/car]
[3] => [car]Corvette[/car]
[4] => [motorcycle]Yamaha[/motorcycle]
[5] => [motorcycle]Ducati[/motorcycle]
[6] => [motorcycle]Gilera[/motorcycle]
[7] => [motorcycle]Kawasaki[/motorcycle]
)
Next, loop over the array and pull out the appropriate pieces needed to build the final associative array using the preg_match function with a regular expression:
$finalArray = [];
foreach($items as $item)
{
//Use preg_match to capture the pieces of the string we want using a regular expression.
//The first capture will grab the text of the tag itself.
//The second capture will grab the text between the opening and closing tag.
//The resulting captures are placed into the matches array.
preg_match("/\[(.*?)\](.*?)\[/", $item, $matches);
//Build the final array structure.
$finalArray[$matches[1]] = $matches[2]
}
The following is an example of what will be found in the matches array for a given iteration of the foreach loop.
Array
(
[0] => [motorcycle]Gilera[
[1] => motorcycle
[2] => Gilera
)
Please note that I use the PHP_EOL constant to explode the initial string. This may not work if the string was pulled from a different operating system than the one you are running this code on. You may need to replace this with the actual end of line characters that is being used by the string.
Why don't you create two separate arrays?
$cars = array("Ford", "Dodge", "Chevrolet", "Corvette");
$motorcycle = array("Yamaha", "Ducati", "Gilera", "Kawasaki");
You could also use an Associative array to do this.
$variable = array("Ford"=>"car", "Yamaha"=>"motorbike");

php reassign array contents [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
any particular function or code to put this kind of array data
ori [0] => 43.45,33,0,35 [1] => 74,10,0,22 [2] => 0,15,0,45 [3] => 0,0,0,340 [4] => 12,5,0,0 [5] => 0,0,0,0
to
new [0] => 43.45,74,0,0,12,0 [1] => 33,10,15,0,5,0 [2] => 0,0,0,0,0,0, [3] => 35,22,45,340,0,0
As you can see, the first value from each ori are inserted into the new(0), the second value from ori are inserted into new(1) and so on
If $ori is an array of arrays, this should work:
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
$newArray = transpose($ori);
Note: from Transposing multidimensional arrays in PHP
If $ori is not an array of arrays, then you'll need to convert it first (or use the example by Peter Ajtai), like this:
// Note: PHP 5.3+ only
$ori = array_map(function($el) { return explode(",", $el); }, $ori);
If you are using an older version of PHP, you should probably just use the other method!
You essentially want to transpose - basically "turn" - an array. Your array elements are strings and not sub arrays, but those strings can be turned into sub arrays with explode() before transposing. Then after transposing, we can turn the sub arrays back into strings with implode() to preserve the formatting you want.
Basically we want to go through each of your five strings of comma separated numbers one by one. We take each string of numbers and turn it into an array. To transpose we have to take each of the numbers from a string one by one and add the number to a new array. So the heart of the code is the inner foreach(). Note how each number goes into a new sub array, since $i is increased by one between each number: $new[$i++][] =$op;
foreach($ori as $one) {
$parts=explode(',',$one);
$i = 0;
foreach($parts as $op) {
$new[$i++][] =$op;
}
}
$i = 0;
foreach($new as $one) {
$new[$i++] = implode(',',$one);
}
// print_r for $new is:
Array
(
[0] => 43.45,74,0,0,12,0
[1] => 33,10,15,0,5,0
[2] => 0,0,0,0,0,0
[3] => 35,22,45,340,0,0
)
Working example

Categories