$products = Array ( [products] => Array ( [0] => 12,11,10 [1] => 16,15,14 [2] => 600,103,20 ) );
foreach($products as $k=>$v)
{
$product_id = $v[0];
$product_weight_id = $v[1];
$product_quantity = $v[2];
}
output required like:
12 16 600
11 15 103
10 14 20
current output :
12,11,10 16,15,14 600,103,20
Update:
If you want to generate a different output, next example may help:
PHP:
<?php
$products = array(
'12,11,10',
'16,15,14',
'600,103,20'
);
$output = array();
foreach($products as $product) {
$a = explode(',', $product);
foreach ($a as $key => $value) {
$output[$key][] = $value;
}
}
foreach($output as $line) {
echo implode(' ', $line)."<br>";
}
?>
Output:
12 16 600
11 15 103
10 14 20
Original answer:
Next example demonstrates two possible approaches to get an output from your array.
PHP:
<?php
$products = array(
'12,11,10',
'16,15,14',
'600,103,20'
);
// Complex approach
foreach($products as $product) {
$a = explode(',', $product);
foreach ($a as $value) {
echo $value." ";
}
echo "<br>";
}
// Simple approach
foreach($products as $product) {
echo $product."<br>";
}
?>
Output:
12 11 10
16 15 14
600 103 20
12,11,10
16,15,14
600,103,20
Please see below code.
$products = array (
'0' => '12,11,10',
'1' => '16,15,14',
'2' => '600,103,20'
);
$productIds = array();
$productWeights = array();
$productQuantities = array();
foreach( $products as $k => $v ) {
$line = explode(',', $v );
$productIds[] = $line[0];
$productWeights[] = $line[1];
$productQuantities[] = $line[2];
}
echo implode( ' ', $productIds);
echo '<br />';
echo implode( ' ', $productWeights);
echo '<br />';
echo implode( ' ', $productQuantities);
echo '<br />';
Using array_map() and implode() you can do it easily. Example:
$products = [[12,11,10], [16,15,14], [600,103,20]];
echo implode('<br />', array_map(function ($arr) { return implode(' ', $arr); }, $products));
Working demo.
Related
I am looking to store sum of all keys inside an array here is my example code
<?php
// Sample data
$category = (object) ['category_name' => '32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1'];
// process
$category_sale_data = explode(',', $category->category_name);
foreach ($category_sale_data as $key => $value) {
list($sale_key, $sale_value) = explode('*', $value);
$category->sale_data[$sale_key][] = $sale_value;
//$category->sale_data_sum[$sale_key][] += $sale_value;
}
// display
print_r($category);
getting this output working example -> https://3v4l.org/NAKfb#v7.0.0
Here is expected to get //$category->sale_data_sum[$sale_key][] +=
$sale_value;
I am expected output like this
stdClass Object
(
[category_name] => 32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1
[sale_data] => Array
(
[32459] => Array
(
[0] => 1500
)
[32460] => Array
(
[0] => 400
)
[32461] => Array
(
[0] => 600
)
)
[sale_data_sum] => 2500
)
Simply do this:
$category->sale_data_sum = 0; // initiate key
foreach ($category_sale_data as $key => $value) {
list($sale_key, $sale_value) = explode('*', $value);
$category->sale_data[$sale_key][] = $sale_value;
$category->sale_data_sum += $sale_value; // add each sale value
}
$category = [ 'category_name' => '32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1' ];
// category_name
$result['category_name'] = $category['category_name'];
// sale_data
$splitted = preg_split('/[*,]/', $category['category_name']);
for($i = 0; $i < count($splitted); $i += 4) {
$result['sale_data'][$splitted[$i]] = $splitted[$i + 1];
}
// sale_data_sum
$result['sale_data_sum'] = array_sum($result['sale_data']);
print_r($result);
Try this
<?php
// Sample data
$category = (object) ['category_name' => '32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1'];
// process
$category_sale_data = explode(',', $category->category_name);
foreach ($category_sale_data as $key => $value) {
list($sale_key, $sale_value) = explode('*', $value);
$category->sale_data[$sale_key][] = $sale_value;
//$category->sale_data_sum[$sale_key][] += $sale_value;
}
function sum($carry, $item)
{
$carry += array_values($item)[0];
return $carry;
}
$a = array_reduce(array_values($category->sale_data), "sum");
var_dump($a);
Or
<?php
// Sample data
$category = (object) ['category_name' => '32459*1500*lab*1,32460*400*lab*1,32461*600*lab*1'];
// process
$category_sale_data = explode(',', $category->category_name);
$category->sale_data_sum = null;
foreach ($category_sale_data as $key => $value) {
list($sale_key, $sale_value) = explode('*', $value);
$category->sale_data[$sale_key][] = $sale_value;
$category->sale_data_sum += $sale_value;
}
// display
print_r($category);
Say I have this PHP array()
$tour_from array
Array
(
[0] => Array
(
[0] => Dhaka
[1] => noakhali
)
[1] => Array
(
[0] => Chittagong
[1] => Sylhet
)
)
I want to make like this:
Dhaka - Noakhali
Chittagong - Sylhet
How can I do this?
I used this but it's the wrong way:
foreach ($tour_from as $key => $value) {
$chunk = array_chunk($value, 2);
foreach ($chunk as $key1 => $value1) {
echo $value1[$key][$key1] . ' - ' . $chunk[$key][$key1];
echo '<br/>';
}
}
I think you're overcomplicating it a bit. Why not just loop over the outer array and implode the inner array?
<?php
$tour_from = [
['Dhaka', 'Noakhali'],
['Chittagong', 'Sylhet'],
];
foreach ($tour_from as $elem) {
print implode(' - ', $elem);
print '<br>';
}
There is no need for chunking or a second loop.
One loop containing implode() will do.
Code: (Demo)
$tour_from = [
['Dhaka', 'Noakhali'],
['Chittagong', 'Sylhet']
];
foreach ($tour_from as $row) {
echo implode(' - ', $row), "\n";
}
Output:
Dhaka - Noakhali
Chittagong - Sylhet
Alternatively, if you like a functional one-liner: (Demo)
echo implode("<br>", array_map(function($row){ return implode(' - ', $row); }, $tour_from));
*The advantage to this is there is no trailing <br> on the final imploded string.
Or with fewer function calls, here is a version with array_reduce(): (Demo)
echo array_reduce($tour_from, function($carry, $row) {
return $carry .= ($carry !== null ? "<br>\n" : '') . $row[0] . ' - ' . $row[1];
});
If you want to avoid using foreach you can do the same thing with array_walk and pass by reference &$var.
$array = [
["Dhaka", "noakhali"],
["Chittagong", "Sylhet"]
];
array_walk($array, function(&$item){
$item = implode(' - ', $item);
});
print_r($array);
Output:
Array
(
[0] => Dhaka - noakhali
[1] => Chittagong - Sylhet
)
Sandbox
If you want to output it instead of modify the array you can just echo it instead or do something like implode('<br>', $array) afterwords.
OH, Yes, I found the way:
foreach ($tour_from as $key => $value) {
$chunk = array_chunk($value, 2);
foreach ($chunk as $key1 => $value1) {
echo implode(' - ', $value1);
echo '<br/>';
}
}
PHP seperate number using based on 2 delimiter
I have this variable $sid
$sid = isset($_POST['sid']) ? $_POST['sid'] : '';
and it's output is:
Array
(
[0] => 4|1
[1] => 5|2,3
)
Now I want to get the 1, 2, 3 as value so that I can run a query based on this number as ID.
How can I do this?
Use explode()
$arr = array(
0 => "4|1",
1=> "5|2,3"
);
$output = array();
foreach($arr as $a){
$right = explode("|",$a);
$rightPart = explode(",",$right[1]);
foreach($rightPart as $rp){
array_push($output,$rp);
}
}
var_dump($output);
Use foreach to loop thru your array. You can explode each string to convert it to an array. Use only the 2nd element of the array to merge
$sid = array('4|1','5|2,3');
$result = array();
foreach( $sid as $val ) {
$val = explode('|', $val, 2);
$result = array_merge( $result, explode(',', $val[1]) );
}
echo "<pre>";
print_r( $result );
echo "</pre>";
You can also use array_reduce
$sid = array('4|1','5|2,3');
$result = array_reduce($sid, function($c, $v){
$v = explode('|', $v, 2);
return array_merge($c, explode(',', $v[1]));
}, array());
These will result to:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
You can do 2 explode with loop to accomplish it.
foreach($sid as $a){
$data = explode("|", $a)[1];
foreach(explode(",", $data) as $your_id){
//do you stuff with your id, for example
echo $your_id . '<br/>';
}
}
$Ascore = 30;
$Bscore = 30;
$Cscore = 20;
$Dscore = 20;
$score = array(
'As' => $Ascore,
'Bs' => $Bscore,
'Cs' => $Cscore,
'Ds' => $Dscore
);
$match = 0;
foreach($score as $key => $val){
if($val > $match){
$match = $val;
}
}
echo $match;
my intention is to find highers score that match , for example highers score = 30 ,As and Bs matched , echo out As = 30 , Bs = 30. so if any 2 of the highers score in the array and having the same highers score, echo both of them. only echo them out if they have same highers score.
Try the following:
$scores = [
'As' => $Ascore,
'Bs' => $Bscore,
'Cs' => $Cscore,
'Ds' => $Dscore,
];
$highest = max($scores);
foreach ($scores as $key => $val)
if ($val === $highest)
echo $key . ' = ' . $val . ', ';
Alternate if the trailing comma IS an issue:
$highest = max($scores);
$victors = [];
foreach ($scores as $key => $val)
if ($val === $highest)
$victors[] = $key . ' = ' . $val;
echo implode(', ', $victors);
I have an array like:
Array
(
[0] => Array
(
[kanal] => TV3+
[image] => 3Plus-Logo-v2.png
)
[1] => Array
(
[kanal] => 6\'eren
[image] => 6-eren.png
)
[2] => Array
(
[kanal] => 5\'eren
[image] => 5-eren.png
)
)
It may expand to several more subarrays.
How can I make a list like: TV3+, 6'eren and 5'eren?
As array could potentially be to further depths, you would be best off using a recursive function such as array_walk_recursive().
$result = array();
array_walk_recursive($inputArray, function($item, $key) use (&$result) {
array_push($result, $item['kanal']);
}
To then convert to a comma separated string with 'and' separating the last two items
$lastItem = array_pop($result);
$string = implode(',', $result);
$string .= ' and ' . $lastItem;
Took some time but here we go,
$arr = array(array("kanal" => "TV3+"),array("kanal" => "5\'eren"),array("kanal" => "6\'eren"));
$arr = array_map(function($el){ return $el['kanal']; }, $arr);
$last = array_pop($arr);
echo $str = implode(', ',$arr) . " and ".$last;
DEMO.
Here you go ,
$myarray = array(
array(
'kanal' => 'TV3+',
'image' => '3Plus-Logo-v2.png'
),
array(
'kanal' => '6\'eren',
'image' => '6-eren.png'
),
array(
'kanal' => '5\'eren',
'image' => '5-eren.png'
),
);
foreach($myarray as $array){
$result_array[] = $array['kanal'];
}
$implode = implode(',',$result_array);
$keyword = preg_replace('/,([^,]*)$/', ' & \1', $implode);
echo $keyword;
if you simply pass in the given array to implode() function,you can't get even the value of the subarray.
see this example
assuming your array name $arr,codes are below
$length = sizeof ( $arr );
$out = '';
for($i = 0; $i < $length - 1; $i ++) {
$out .= $arr [$i] ['kanal'] . ', ';
}
$out .= ' and ' . $arr [$length - 1] ['kanal'];
I think it would work to you:
$data = array(
0 =>['kanal' => 'TV1+'],
1 =>['kanal' => 'TV2+'],
2 =>['kanal' => 'TV3+'],
);
$output = '';
$size = sizeof($data)-1;
for($i=0; $i<=$size; $i++) {
$output .= ($size == $i && $i>=2) ? ' and ' : '';
$output .= $data[$i]['kanal'];
$output .= ($i<$size-1) ? ', ' : '';
}
echo $output;
//if one chanel:
// TV1
//if two chanel:
// TV1 and TV2
//if three chanel:
// TV1, TV2 and TV3
//if mote than three chanel:
// TV1, TV2, TV3, ... TV(N-1) and TV(N)
$last = array_slice($array, -1);
$first = join(', ', array_slice($array, 0, -1));
$both = array_filter(array_merge(array($first), $last));
echo join(' and ', $both);
Code is "stolen" from here: Implode array with ", " and add "and " before last item
<?php
foreach($array as $arr)
{
echo ", ".$arr['kanal'];
}
?>