This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I am selecting values from my database, when I dump the $results I get;
array (
0 =>
(object) array(
'FieldName' => 'certification_name',
'FieldValue' => 'White Belt',
),
1 =>
(object) array(
'FieldName' => 'certification_name',
'FieldValue' => 'Yellow Belt',
),
)
I want to display the following on my page;
Certification List: White Belt, Yellow Belt
I have created a loop but when I echo the result I get this;
Certification List: Array Array
My PHP code;
foreach ($results as $result) {
$name = $result->FieldName;
$value = $result->FieldValue;
$items[] = array(
'name' => $name,
'value' => $value
);
}
$items = implode("\n", $items);
echo 'Certification List: ' .$items;
What do I need to change in order to get this working?
You shouldn't push arrays into $items, just push the values.
foreach ($results as $result) {
$items[] = $result->FieldValue;
}
$item_list = implode(", ", $items);
echo "Certification List: $item_list";
You can also replace the loop with:
$items = array_column($results, 'FieldValue');
Related
This question already has answers here:
How add a link on comma separated multidimensional array
(2 answers)
Closed 7 months ago.
I am trying to generate a string from an array. Need to concatenate the array values with a small string AFTER the value. It doesn't work for the last value.
$data = array (
1 => array (
'symbol' => 'salad'
),
2 => array (
'symbol' => 'wine'
),
3 => array (
'symbol' => 'beer'
)
);
$symbols = array_column($data, 'symbol');
$string_from_array = join($symbols, 'bar');
echo($string_from_array);
// expected output: saladbar, winebar, beerbar
// output: saladbar, winebar, beer
You can achieve it a few different ways. One is actually by using implode(). If there is at least one element, we can just implode by the delimiter "bar, " and append a bar after. We do the check for count() to prevent printing bar if there are no results in the $symbols array.
$symbols = array_column($data, "symbol");
if (count($symbols)) {
echo implode("bar, ", $symbols)."bar";
}
Live demo at https://3v4l.org/ms5Ot
You can also achieve the desired result using array_map(), as follows:
<?php
$data = [
1 => ['symbol' => 'salad'],
2 => ['symbol' => 'wine'],
3 => ['symbol' => 'beer']
];
echo join(", ", array_map(
fn($v) => "{$v}bar",
array_column($data, 'symbol')
)
);
See live code
Array_map() takes every element of the array resulting from array_column() pulling out the values from $data and with an arrow function, appends the string "bar". Then the new array yielded by array_map has the values of its elements joined with ", " to form the expected output which is then displayed.
As a recent comment indicated you could eliminate array_column() and instead write code as follows:
<?php
$data = [
1 => ['symbol' => 'salad'],
2 => ['symbol' => 'wine'],
3 => ['symbol' => 'beer']
];
echo join(", ", array_map(
fn($row) => "{$row['symbol']}bar",
$data
)
);
See live code
Note while this 2nd way, may appear more direct, is it? The fact is that as array_map iterates over $data, the arrow function contains code that requires dereferencing behind the scenes, namely "$row['symbol']".
The join() function is an alias of implode() which
Returns a string containing a string representation of all the array
elements in the same order, with the glue string between each element.
So you need to add the last one by yourself
$data = array (
1 => array (
'symbol' => 'salad'
),
2 => array (
'symbol' => 'wine'
),
3 => array (
'symbol' => 'beer'
)
);
$symbols = array_column($data, 'symbol');
$string_from_array = join($symbols, 'bar');
if(strlen($string_from_array)>0)
$string_from_array .= "bar";
echo($string_from_array);
You can use array_column and implode
$data = array (
1 => array (
'symbol' => 'salad'
),
2 => array (
'symbol' => 'wine'
),
3 => array (
'symbol' => 'beer'
)
);
$res = implode("bar,", array_column($data, 'symbol'))."bar";
Live Demo
Try this:
$symbols = array_column($data, 'symbol');
foreach ($symbols as $symbol) {
$symbol = $symbol."bar";
echo $symbol;
}
btw, you can't expect implode to do what you expect, because it places "bar" between the strings, and there is no between after the last string you get from your array. ;)
Another way could be using a for loop:
$res = "";
$count = count($data);
for($i = 1; $i <= $count; $i++) {
$res .= $data[$i]["symbol"] . "bar" . ($i !== $count ? ", " : "");
}
echo $res; //saladbar, winebar, beerbar
Php demo
This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I am facing some problem to fix this issue. My array same as below
Array ( [0] => Array ( [coupon] => dasd ) [1] => Array ( [coupon] => aaa ) )
From here I want to display only coupon value as comma separated. Same as below
dasd,aaa
To solve this I tried below code but that's not solving my issue.
<?php
$option_settings = array(
array( 'coupon'=>'dasd'
),
array( 'coupon'=>'aaa')
);
print_r($option_settings );
echo $output = implode(',', $option_settings);
?>
Sample https://eval.in/784206
Try this code
<?php
$option_settings = array(
array( 'coupon'=>'dasd'
),
array( 'coupon'=>'aaa')
);
$arr = array();
foreach($option_settings as $opt) {
$arr[] = $opt['coupon'];
}
echo $output = implode(',', $arr);
?>
Or You can use php function array_column()
$coupans_arr =array_column($option_settings, 'coupon');
echo $output = implode(",", $coupans_arr);
Live Demo
use simple array_column method
$option_settings = array(
array( 'coupon'=>'dasd'
),
array( 'coupon'=>'aaa')
);
print_r($option_settings );
$coupans_arr =array_column($option_settings, 'coupon');
echo $output = implode(",", $coupans_arr);
https://eval.in/784217
This is what you want,
print_r(implode(',', array_column($array, 'coupon')));
Please let me know if this works:
$option_settings = array(
array( 'coupon'=>'dasd'
),
array( 'coupon'=>'aaa')
);
$result = '';
foreach($option_settings as $item)
{
$result .= $item['coupon'] .', ';
}
$result = rtrim($result, ', ');
https://eval.in/784220
I know there may be sources for this out there but I'v tried everything and I'm still not getting the proper solution. That why I'm asking for you help out here.
I have a $_POST array and I want to put values in a an array. Here is the final out I want:
$response = [
['category' => 2, 'value' => "june"],
['category' => 5, 'value' => "may"],
['category' => 8, 'value' => "april"]
]
Here is the catch,the $_POST contains a value of an integer with a space in between and then a string eg '2 june', '5 may' etc
When I get this value, I split it using explode then I try to add the individual values into the response array. This is only adding just one result.
What I tried:
$response = [];
foreach ($_POST as $key => $value) {
$split = explode(" ", $value);
$result = ['category' => $split[0], 'value' => $split[1]];
$response[] = $result;
}
for some reason, the results are not as suggested above. Any ideas and suggestion will be appreciated.
Basically, problem is in the $_POST. This is global array with submitted key-values data. You should NOT use
foreach ($_POST as $key => $value) {
for parsing your data without any checks. This data is submitted by user, and not always they will have format you're waiting for.
For example, if you have a variable "dates" in your HTML form, you should be ready that $_POST['dates'] will be an array of all of your '5 june', '7 july', etc. Don't forget to check and validate all user data you received. It's important by security reason too.
Your code (foreach body, without condition) is ok, I've checked it. Try to set print_r() before explode() you will see that your're working with an array, not with a string.
Your question doesn't have an issue with processing the data into the correct resulting array. The onus falls on $_POST not holding the expected data.
All answers to this question are powerless to fix your $_POST data because no html form was supplied with your question. The only potential value that can be offered is to refine your array building process.
Here are two methods that improve your process by reducing the number of declared variables:
Demonstration uses $a=array('2 june','5 may','8 april'); to represent your $_POST array.
One-liner in a foreach loop:
foreach($a as $v){
$r[]=array_combine(["category","value"],explode(" ",$v));
}
One-liner with no loop:
$r=array_map(function($v){return array_combine(["category","value"],explode(" ",$v));},$a);
Using either process the resulting $r will be:
array (
0 =>
array (
'category' => '2',
'value' => 'june',
),
1 =>
array (
'category' => '5',
'value' => 'may',
),
2 =>
array (
'category' => '8',
'value' => 'april',
),
)
References for used functions:
explode() , array_combine() , array_map()
Try this one:
$response = [];
// just for example use this one
$data = "2 june, 5 may, 7 july";
$temp = explode(",", $data);
// and you can use this one for your case
/*$data = $_POST['var_name']; // var_name is your variable name from $_POST
$temp = explode(",", $data);*/
foreach ($temp as $key => $value) {
$split = explode(" ", trim($value));
foreach ($split as $val) {
$result = ['category' => $split[0], 'value' => $split[1]];
}
$respon[] = $result;
}
echo "<pre>";
echo print_r($respon);
echo "</pre";
the output:
Array
(
[0] => Array
(
[category] => 2
[value] => june
)
[1] => Array
(
[category] => 5
[value] => may
)
[2] => Array
(
[category] => 7
[value] => july
)
)
$response = array();
foreach ($_POST as $key => $value) {
$split = '';
$split = explode(" ", $value);
$result = array('category' => $split[0], 'value' => $split[1]);
$response[] = $result;
}
This question already has answers here:
Turning multidimensional array into one-dimensional array [duplicate]
(11 answers)
Closed 4 years ago.
I need to flatten an array while making sure that there are no duplicate keys.
For instance let's say I have this:
$arr = array(
$foo = array(
'donuts' => array(
'name' => 'lionel ritchie',
'animal' => 'manatee',
)
)
);
I need a flattened array that looks like this:
$arr = array(
'donuts name' => 'lionel ritchie',
'donuts animal' => 'manatee',
);
It needs to work even if we have more than 1 parent keys.
I have the following code, but I am not sure I can work with this.
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array1)) as $k=>$v){
$array1c[$k] = $v;
}
It's very simple to do, just make it like this:
$arr = array(
$foo = array(
'donuts' => array(
'name' => 'lionel ritchie',
'animal' => 'manatee',
)
)
);
// Will loop 'donuts' and other items that you can insert in the $foo array.
foreach($foo as $findex => $child) {
// Remove item 'donuts' from array, it will get the numeric key of current element by using array_search and array_keys
array_splice($foo, array_search($findex, array_keys($foo)), 1);
foreach($child as $index => $value) {
// Adds an array element for every child
$foo[$findex.' '.$index] = $value;
}
}
Result of var_dump($foo); will be:
array(2) {
["donuts name"]=>
string(14) "lionel ritchie"
["donuts animal"]=>
string(7) "manatee"
}
Just try :)
This question already has answers here:
PHP search array in array
(3 answers)
Closed 8 years ago.
I have an array:
$members = array(
'Group1' => array(
'user1',
'user2'
),
'Group2' => array(
'user3',
'user4'
),
'Group3' => array(
'user5'
));
How can I search group name for specific user ?
Simplest (logic wise) way is a quick foreach loop with an in_array() check to find whether or not your name is in the sub array:
$search = 'user4';
foreach($members as $group_name => $names)
if(in_array($search, $names))
echo $search . ' is in ' . $group_name; // user4 is in Group2
Example: https://eval.in/148332
Assuming a user may occur in multiple groups:
$groups = array();
foreach ($members as $group_name => $group_members) {
if (in_array('user4', $group_members)) {
$groups[] = $group_name;
}
}
The variable $groups will contain all the group names that matched, though in the above example that's only "Group2".