How to make the array value comma separated - php

How can I make the values of array comma separated values?
this is my array:
array(
'product_name' =>
0 => 'pn1',
1 => 'pn2'
'supply_product_name' =>
0 => 'ps1'
'custom_product_code' =>
0 => string 'cpc1'
)
how to achieve to look like these:
array(
'product_name' => 'pn1, pn2' ,
'supply_product_name' => 'ps1' ,
'custom_product_code' => 'cpc1'
)

Try these code:
$arr = array(
'product_name' => ['pn1', 'pn2'],
'supply_product_name' => ['ps1'],
'custom_product_code' => ['cpc1']
);
foreach($arr as $key => $val)
{
$arr[$key] = implode($val, ',');
}
var_dump($arr);

Related

Writing a HTML string content with array values in Laravel Controller

What I'm trying to accomplish is to write a html string in a controller with array values being looped in it. So for example;
$content = "Your store, at location A, has these items added to them". add array loop here. "Do take note!";
My array would be as such
array (
0 =>
array (
'id' => '5db29b6d31c391731239bbdf',
'name' => 'Diamond bracelet (sample)',
'tags' =>
array (
0 => 'female',
1 => 'jewelry',
),
'category' => 'Accessories',
'sku' => '1029EHW',
'priceType' => 'Fixed',
'unitPrice' => 190,
'cost' => 90,
'trackStockLevel' => true,
'isParentProduct' => false,
),
1 =>
array (
'id' => '5db29b6d31c391731239bbdb',
'name' => 'Long-sleeved shirt(sample)(M)',
'tags' =>
array (
0 => 'tops',
1 => 'cotton',
),
'category' => 'Women\'s Apparel',
'sku' => 'ABC1234-M',
'priceType' => 'Fixed',
'unitPrice' => 47.170000000000002,
'cost' => 20,
'trackStockLevel' => true,
'isParentProduct' => false,
'parentProductId' => '5db29b6d31c391731239bbd4',
'variationValues' =>
array (
0 =>
array (
'variantGroupId' => '5db29b6d31c391731239bbd5',
'value' => 'M',
),
),
),
)
note that the array can have many instances of product_name and sku, or can have none.
How do i populate this in my string to be like;
$content = "Your store, at location A, has these items added to them, 1) asd, 2)def, 3)asf . Do take note!
Try this, I've used \sprintf for ease, check if the output serves your purpose.
<?php
function stringMethod(): string
{
$count = 0;
$arrayString = [];
$array = [['product_name' => 'abc', 'product_sku' => 'def'],['product_name' => 'abc', 'product_sku' => 'asd']];
foreach ($array as $value){
$count++;
$arrayString[] = sprintf('%s)%s', $count, $value['product_sku']);
}
$string = \implode(',', $arrayString);
return \sprintf("Your store, at location A, has these items added to them %s Do take note!", $string);
}
echo stringMethod();
Hope this will help you. try to do it in less number of lines
$content = "Your store, at location A, has these items added to them, ";
$productArray = array (0 => array ('id' => '5db29b6d31c391731239bbdf','name' => 'Diamond bracelet (sample)','tags' => array (0 => 'female',1 => 'jewelry',),'category' => 'Accessories','sku' => '1029EHW','priceType' => 'Fixed','unitPrice' => 190,'cost' => 90,'trackStockLevel' => true,'isParentProduct' => false,),1 => array ('id' => '5db29b6d31c391731239bbdb','name' => 'Long-sleeved shirt(sample)(M)','tags' => array (0 => 'tops',1 => 'cotton',),'category' => 'Women\'s Apparel','sku' => 'ABC1234-M','priceType' => 'Fixed','unitPrice' => 47.170000000000002,'cost' => 20,'trackStockLevel' => true,'isParentProduct' => false,'parentProductId' => '5db29b6d31c391731239bbd4','variationValues' => array (0 => array ('variantGroupId' => '5db29b6d31c391731239bbd5','value' => 'M'))));
foreach ($productArray as $key => $product) {
$content .= ($key+1).') '.$product['name'];
if (count($productArray)-1!=$key) {
$content .= ', ';
}
}
$content .= ". Do take note!";
$content = "Your store, at location A, has these items added to them,". $this->getItemList($collection) .". Do take note!"
# Somewhere else in the controller
protected function getItemList(Collection $collection): string
{
return $collection->pluck('name')
->merge($collection->pluck('sku'))
->map(function($item, $key) {
return ($key + 1) . ') ' . $item;
})
->implode(', ');
}
An easy solution would be
$content = "Your store, at location A, has these items added to them";
$array = array(0=>["product_name" => "abc", "product_sku" => "def"], 1=>['product_name' => 'kdkf', 'product_sku'=> 'ljbkj']);
for($i = 0; $i<count($array); $i++){
$content .= ($i+1).") ".$array[$i]['product_name].' '.$array[$i]['product_sku'].', ';
}
$content .= "Do take note.";
This way you're just constantly concatonating the string value in separate parts instead of trying to inject it in the middle of the parent string.
not tested, may be syntax errors

PHP group keys in array with multiple values

I've got an array like this:
$sendemail= array(
'apple#yahoo.com' => '123456781234567',
'apple#yahoo.com' => '013881002296968',
'cherry#yahoo.com' => '3553220865206561',
'orange#yahoo.com' => '358805051217453',
'apple#yahoo.com' => '357998054217777',
'cherry#yahoo.com' => '013881002296968',
);
I would like to have an output like this:
'apple#yahoo.com' => 123456781234567, 013881002296968, 357998054217777
'cherry#yahoo.com' => 3553220865206561, 013881002296968
'orange#yahoo.com' => 358805051217453
to be able to use the keys as email address and the values as my email's buddy
$email= 'apple#yahoo.com';
$body= '123456781234567, 013881002296968, 357998054217777';
mail($email, 'Your codes', $body);
And the same for the other email addresses.
PLEASE NOTE that 2 keys might have the same values which is fine (e.g. apple#yahoo.com and cherry#yahoo.com have the same values; the value will be sent to both of them)
I used this 'for loop' but didn't work. first of all I cant group them based on email addresses, second of all the same values will not be assigned to the other email addresses; like '013881002296968' which should be shared with apple#yahoo.com and cherry#yahoo.com
$sendmail= array(
'123456781234567' => 'apple#yahoo.com',
'013881002296968' => 'apple#yahoo.com',
'3553220865206561' => 'cherry#yahoo.com',
'358805051217453' => 'orange#yahoo.com',
'357998054217777' => 'apple#yahoo.com',
'013881002296968' => 'cherry#yahoo.com',
);
$out = array();
foreach($sendmail as $key=>$value)
if(array_key_exists($value, $out)) {
$out[$value][] = $key;
}
else {
$out[$value] = array($key);
}
Output
array (
'apple#yahoo.com' =>
array (
0 => 123456781234567,
1 => 013881002296968,
2 => 357998054217777,
),
'cherry#yahoo.com' =>
array (
0 => 3553220865206561,
),
'orange#yahoo.com' =>
array (
0 => 358805051217453,
),
)
Here is an alternative to Kris' method that has less iterations, but more conditionals:
Input:
$sendmail= array(
'123456781234567' => 'apple#yahoo.com',
'013881002296968' => 'apple#yahoo.com',
'3553220865206561' => 'cherry#yahoo.com',
'358805051217453' => 'orange#yahoo.com',
'357998054217777' => 'apple#yahoo.com',
'013881002296968' => 'cherry#yahoo.com',
);
Method:
foreach($sendmail as $k=>$v){
if(!isset($out[$v])){$out[$v]='';} // initialize new element with empty string
$out[$v].=($out[$v]?',':'').$k; // concat the values with conditional comma
}
var_export($out);
Output:
array (
'apple#yahoo.com' => '123456781234567,357998054217777',
'cherry#yahoo.com' => '013881002296968,3553220865206561',
'orange#yahoo.com' => '358805051217453',
)
Use implode on the element of your result array. live demo
foreach($sendmail as $key=>$value) {
$out[$value][] = $key;
}
$out = array_map(function($v){return implode(',', $v);}, $out);

Modifying multidimensional array in PHP replacing keys as the values [duplicate]

This question already has answers here:
How to swap keys with values in array?
(6 answers)
Closed 6 years ago.
How would you modify the following code using only a foreach loop by replacing the keys as the values? For examples the salad, chicken, and pancakes keys would the values instead.
$meals = array(
'Lunch' => array(
'salad' => 'italian',
'salad2' => 'ranch',
'salad3' => 'sesame',
'salad4' => 'bluecheese'
),
'Dinner' => array(
'chicken' => 'grilled',
'chicken2' => 'baked',
'chicken3' => 'steamed',
'chicken4' => 'fried',
'chicken5' => 'broiled'
),
'Breakfast' => array(
'pancakes' => 'blueberry',
'pancakes2' => 'cherry',
'pancakes3' => 'strawberry',
'pancakes4' => 'lemon'
)
);
$newkey = array();
foreach($meals as $key => $value) {
unset($value);
// foreach ($)...
}
print_r($meals);
Edit
If you're unable to use array_flip(), then you'll need to do two loops: one for each meal, and one for each meal option.
Example:
foreach ($meals as $meal => $mealOptions)
{
$revisedMealOptions = array();
foreach ($mealOptions as $originalKey => $newKey)
{
$revisedMealOptions[$newKey] = $originalKey;
}
$meals[$meal] = $revisedMealOptions;
}
Original Answer
It's not entirely clear what you're after. If all you want is to turn:
'Lunch' => array(
'salad' => 'italian'
);
into
'Lunch' => array(
'italian' => 'salad'
);
use array_flip().
Example:
$meals['Lunch'] = array_flip($meals['Lunch']);
See http://php.net/manual/en/function.array-flip.php.
I'm sorry I am a total beginner. I need to use a nested $foreach loop to address this question. For class I'm not allowed to use the array_flip function. I have tried
$newkey = array();
foreach($meals as $key => $value) {
$newkey[] = $value;
foreach ($value as ){
}
}
So, it would read:
Basically I need it to read:
Array(
[Lunch] => array(
[italian] => salad,
[ranch] => salad2,
[sesame] => salad3,
[bluecheese] => salad4
)
)
The easiest way to do it would be like this:
$meals = array(
'Lunch' => array(
'salad' => 'italian',
'salad2' => 'ranch',
'salad3' => 'sesame',
'salad4' => 'bluecheese'
),
'Dinner' => array(
'chicken' => 'grilled',
'chicken2' => 'baked',
'chicken3' => 'steamed',
'chicken4' => 'fried',
'chicken5' => 'broiled'
),
'Breakfast' => array(
'pancakes' => 'blueberry',
'pancakes2' => 'cherry',
'pancakes3' => 'strawberry',
'pancakes4' => 'lemon'
)
);
$newArray = array();
foreach ($meals as $key => $value) {
$temp = array();
foreach ($value as $innerKey => $innerValue) {
$temp[$innerValue] = $innerKey;
}
$newArray[$key] = $temp;
}
unset($meals);
Basically, you create a new array and build it from the beginning with the use of the array $meals.

array sort by keys.

I have a following array,
$versions = array
(
'0.9.md5' => '/var/www/md5_test/0.9.md5',
'1.0.0.md5' => '/var/www/md5_test/1.0.0.md5',
'1.0.1.md5' => '/var/www/md5_test/1.0.1.md5',
'1.0.2.md5' => '/var/www/md5_test/1.0.2.md5',
'1.0.3.md5' => '/var/www/md5_test/1.0.3.md5',
'1.0.9.1.md5' => '/var/www/md5_test/1.0.9.1.md5',
'1.0.9.10.1.md5' => '/var/www/md5_test/1.0.9.10.1.md5',
'1.0.9.10.md5' => '/var/www/md5_test/1.0.9.10.md5',
'1.1.3.md5' => '/var/www/md5_test/1.1.3.md5',
'1.0.9.2.md5' => '/var/www/md5_test/1.0.9.2.md5',
'1.0.9.3.md5' => '/var/www/md5_test/1.0.9.3.md5',
'1.0.9.8.md5' => '/var/www/md5_test/1.0.9.8.md5',
'1.0.9.9.1.md5' => '/var/www/md5_test/1.0.9.9.1.md5',
'1.0.9.9.md5' => '/var/www/md5_test/1.0.9.9.md5',
'1.0.9.md5' => '/var/www/md5_test/1.0.9.md5',
'1.1.0.md5' => '/var/www/md5_test/1.1.0.md5',
'1.1.1.md5' => '/var/www/md5_test/1.1.1.md5',
'1.1.2.md5' => '/var/www/md5_test/1.1.2.md5',
);
In this array i want to sort this by keys. I have searched,
Ex: It should order like: 1.0.9.md5, 1.0.9.1.md5,.. , 1.0.9.10.md5, 1.0.9.10.1.md5
I have tried
ksort($versions);
But i could't get exactly what i want.
If these are version numbers, and you need to sort by the version so that 1.0.9.2.md5 comes before 1.0.9.10.1.md5 then you need a custom sort based on semantic versioning:
uksort($versions, 'version_compare');
Demo
Remove the ".md5" -> ksort() -> add the ".md5" again.
foreach($versions as $key => $value) {
$newKey = str_replace(".md5", "", $key);
$new[$newKey] = $value;
}
ksort($new);
foreach($new as $key => $value) {
$newKey = $key . ".md5";
$result[$newKey]= $value;
}
print_r($result);
Result:
Array
(
[0.9.md5] => /var/www/md5_test/0.9.md5
[1.0.0.md5] => /var/www/md5_test/1.0.0.md5
[1.0.1.md5] => /var/www/md5_test/1.0.1.md5
[1.0.2.md5] => /var/www/md5_test/1.0.2.md5
[1.0.3.md5] => /var/www/md5_test/1.0.3.md5
[1.0.9.md5] => /var/www/md5_test/1.0.9.md5
[1.0.9.1.md5] => /var/www/md5_test/1.0.9.1.md5
[1.0.9.10.md5] => /var/www/md5_test/1.0.9.10.md5
[1.0.9.10.1.md5] => /var/www/md5_test/1.0.9.10.1.md5
[1.0.9.2.md5] => /var/www/md5_test/1.0.9.2.md5
[1.0.9.3.md5] => /var/www/md5_test/1.0.9.3.md5
[1.0.9.8.md5] => /var/www/md5_test/1.0.9.8.md5
[1.0.9.9.md5] => /var/www/md5_test/1.0.9.9.md5
[1.0.9.9.1.md5] => /var/www/md5_test/1.0.9.9.1.md5
[1.1.0.md5] => /var/www/md5_test/1.1.0.md5
[1.1.1.md5] => /var/www/md5_test/1.1.1.md5
[1.1.2.md5] => /var/www/md5_test/1.1.2.md5
[1.1.3.md5] => /var/www/md5_test/1.1.3.md5
)

how to find a element in a nested array and get its sub array index

when searching an element in a nested array, could i get back it's 1st level nesting index.
<?php
static $cnt = 0;
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
function recursive_search(&$v, $k, $search_query){
global $cnt;
if($v == $search_query){
/* i want the sub array index to be returned */
}
}
?>
i.e to say, if i'am searching 'victor', i would like to have 'dep1' as the return value.
Could anyone help ??
Try:
$name = 'victor';
$coll = array(
'dep1' => array(
'fy' => array('john', 'johnny', 'victor'),
'sy' => array('david', 'arthur'),
'ty' => array('sam', 'joe', 'victor')
),
'dep2' => array(
'fy' => array('natalie', 'linda', 'molly'),
'sy' => array('katie', 'helen', 'sam', 'ravi', 'vipul'),
'ty' => array('sharon', 'julia', 'maddy')
)
);
$iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($coll), RecursiveIteratorIterator::SELF_FIRST);
/* These will be used to keep a record of the
current parent element it's accessing the childs of */
$parent_index = 0;
$parent = '';
$parent_keys = array_keys($coll); //getting the first level keys like dep1,dep2
$size = sizeof($parent_keys);
$flag=0; //to check if value has been found
foreach ($iter as $k=>$val) {
//if dep1 matches, record it until it shifts to dep2
if($k === $parent_keys[$parent_index]){
$parent = $k;
//making sure the counter is not incremented
//more than the number of elements present
($parent_index<$size-1)?$parent_index++:'';
}
if ($val == $name) {
//if the value is found, set flag and break the loop
$flag = 1;
break;
}
}
($flag==0)?$parent='':''; //this means the search string could not be found
echo 'Key = '.$parent;
Demo
This works , but I don't know if you are ok with this...
<?php
$name = 'linda';
$col1=array ( 'dep1' => array ( 'fy' => array ( 0 => 'john', 1 => 'johnny', 2 => 'victor', ), 'sy' => array ( 0 => 'david', 1 => 'arthur', ), 'ty' => array ( 0 => 'sam', 1 => 'joe', 2 => 'victor', ), ), 'dep2' => array ( 'fy' => array ( 0 => 'natalie', 1 => 'linda', 2 => 'molly', ), 'sy' => array ( 0 => 'katie', 1 => 'helen', 2 => 'sam', 3 => 'ravi', 4 => 'vipul', ), 'ty' => array ( 0 => 'sharon', 1 => 'julia', 2 => 'maddy', ), ), );
foreach($col2 as $k=>$arr)
{
foreach($arr as $k1=>$arr2)
{
if(in_array($name,$arr2))
{
echo $k;
break;
}
}
}
OUTPUT :
dept2
Demo

Categories