I want to limit every array to strings with 15 characters or less. I have tried this code, but it does not work:
$a = [
"name1" => ['Dewa','Aditya','Pratama'],
"name2" => ['Brian','Dzikri','Ramadhan'],
];
$result_shortdes = "";
foreach ($a as $values) {
foreach ($values as $value) {
if(strlen($result_shortdes) + strlen($value) <= 15)
{
$result_shortdes .= "$value,";
}
}
}
echo '<pre>';
print_r($result_shortdes);
echo '<pre>';
My expected output is like this:
1. Dewa,Aditya,
2. Brian,
Every time you go to the next name, you need to reset result_shortdes to count the name length again, place the variable inside the first loop like this:
foreach ($a as $values) {
$result_shortdes = "";
foreach ($values as $value) {
if(strlen($result_shortdes) + strlen($value) <= 15)
{
$result_shortdes .= "$value,";
}
}
echo '<pre>';
print_r($result_shortdes);
echo '<pre>';
}
you can use $result_shortdes for length and $result to store result like below
$a = [
"name1" => ['Dewa','Aditya','Pratama'],
"name2" => ['Brian','Dzikri','Ramadhan'],
];
$result_shortdes = "";
$result = [];
foreach ($a as $values) {
$result_shortdes = "";
foreach ($values as $value) {
if(strlen($result_shortdes) + strlen($value) <= 15)
{
$result_shortdes .= "$value,";
}else{
$result[] = $result_shortdes;
break;
}
}
}
echo '<pre>';
print_r($result);
echo '<pre>';
Related
I'm trying to merge multiple arrays with same keys and add their values if keys exist, if not add a new object. Could not get the logic right on this
these are samle arrays
[{"2":"90"},{"12":"400"},{"25":"750"},{"0":"50"}]
[{"1":"100"},{"23":"200"},{"12":"1000"},{"0":"5"}]
and the expected output is
[{ {"2":"90"},{"12":"1400"},{"25":"750"},{"0":"55"},{"1":"100"},{"23":"200"}]
This is php code i have used
while($row = $result->fetch_assoc())
{
if ($i==0)
{
$rowOut = $row;
$i++;
}else
{
foreach($rowOut as $key1 => $value1) {
foreach($row as $key => $value)
{
if($key == $key1){
(int)$rowOut->$value1 = (int)$value + (int)$value1;
}
}
}
}
}
not the most elegant solution, but it works
$a = [2=>90,12=>400,25=>750,0=>50] ;
$b = [1=>100,23=>200,12=>1000,0=>5];
$ak = array_keys($a);
$bk = array_keys($b);
$ck = array_intersect($ak,$bk);
$out = [];
foreach ($ck as $key => $value)
{
$out[$value] = $a[$value] + $b[$value];
unset($a[$value]);
unset($b[$value]);
}
foreach ($a as $key => $value)
{
$out[$key] = $value;
}
foreach ($b as $key => $value)
{
$out[$key] = $value;
}
var_dump($out);
You may concat the two arrays and use reduce to construct the new array.
demo
<?php
$array1 = [
["2" => "90"],
["12" => "400"],
["25" => "750"],
["0" => "50"]
];
$array2 = [
["1" => "100"],
["23" => "200"],
["12" => "1000"],
["0" => "5"]
];
$concat = [...$array1, ...$array2];
$reduce = array_reduce($concat, function ($carry, $item) {
$key = array_keys($item)[0];
if (isset($carry[$key])) {
$carry[$key][$key] += $item[$key];
} else {
$carry[$key] = [$key => $item[$key]];
}
$carry[$key][$key] = (string)$carry[$key][$key];
return $carry;
}, []);
$output = array_values($reduce);
echo var_dump($output);
How do I solve the following problem using PHP RecursiveIteratorIterator?
$arr = array(
"sum"=>array(2,4,6, "multiply" => array(1,3,5) ),
"multiply"=>array(3,3,3, "sum" => array(2,4,6) ),
);
I am expecting the following answers
(2 + 4 + 6 + ( 1 * 3 * 5) ) = 27;
(3 * 3 * 3 * (2 + 4 + 6)) = 324;
Partial code so far..
$calc = new ArrayObject($arr);
$MRI = new RecursiveIteratorIterator(new MyRecursiveIterator($calc), 1);
foreach ($MRI as $key=>$value) {
echo " Current Depth: ". $MRI->getDepth() . "\n";
echo $key . " : " . $value . "\n";
$currentDepth = $MRI->getDepth();
for ($subDepth = $currentDepth; $subDepth >= 0; $subDepth--)
{ echo "sub Depth: ". $subDepth . "\n";
$subIterator = $MRI->getSubIterator($subDepth);
// var_dump($subIterator); } }
You can do it like this, do the calculation from the innermost of the array. Check the demo.
<?php
function f(&$array)
{
foreach($array as $k => &$v)
{
if(is_array($v))
{
if(count($v) == count($v, 1))
{
unset($array[$k]);
if($k == 'sum')
{
$v = array_sum($v);
$array[] = $v;
}elseif($k == 'multiply'){
$v = array_product($v);
$array[] = $v;
}else{
foreach($v as $vv)
$array[] = $vv;
}
}else
f($v);
}
}
}
while(count($array) != count($array, 1))
{
f($array);
}
print_r($array);
Noteļ¼
traverse array from outer to inner
traverse array from inner to outer
Simple and easy solution :-
$arr = array("sum"=>array(2,4,6, "multiply" => array(1,3,5) ),"multiply"=>array(3,3,3, "sum" => array(2,4,6)));
foreach($arr as $key => $newarr){
if($key =="sum"){
$sum = array_sum($newarr);
$product = array_product($newarr['multiply']);
$finalarray[$key] = $sum+$product;
}elseif($key =="multiply") {
$product = array_product($newarr);
$sum = array_sum($newarr['sum']);
$finalarray[$key] = $sum*$product;
}
}
echo "<pre>"; print_r($finalarray);
Hope it helps!
$array = ['coke.','fanta.','chocolate.'];
foreach ($array as $key => $value) {
if (strlen($value)<6) {
$new[] = $value." ".$array[$key+1];
} else {
$new[] = $value;
}
}
This code doesn't have the desired effect, in fact it doesn't work at all. What I want to do is if an array element has string length less than 5, join it with the next element. So in this case the array should turn into this:
$array = ['coke. fanta.','chocolate.'];
$array = ['coke.','fanta.','chocolate.', 'candy'];
$new = [];
reset($array); // ensure internal pointer is at start
do{
$val = current($array); // capture current value
if(strlen($val)>=6):
$new[] = $val; // long string; add to $new
// short string. Concatenate with next value
// (note this moves array pointer forward)
else:
$nextVal = next($array) ? : '';
$new[] = trim($val . ' ' . $nextVal);
endif;
}while(next($array));
print_r($new); // what you want
Live demo
With array_reduce:
$array = ['coke.', 'fanta.', 'chocolate.', 'a.', 'b.', 'c.', 'd.'];
$result = array_reduce($array, function($c, $i) {
if ( strlen(end($c)) < 6 )
$c[key($c)] .= empty(current($c)) ? $i : " $i";
else
$c[] = $i;
return $c;
}, ['']);
print_r($result);
demo
<pre>
$array = ['coke.','fanta.','chocolate.'];
print_r($array);
echo "<pre>";
$next_merge = "";
foreach ($array as $key => $value) {
if($next_merge == $value){
continue;
}
if (strlen($value)<6) {
$new[] = $value." ".$array[$key+1];
$next_merge = $array[$key+1];
} else {
$new[] = $value;
}
}
print_r($new);
</pre>
Updated Code after adding pop after chocolate.
<pre>
$array = ['coke.','fanta.','chocolate.','pop'];
print_r($array);
echo "<br>";
$next_merge = "";
foreach ($array as $key => $value) {
if($next_merge == $value){
continue;
}
if (strlen($value)<6 && !empty($array[$key+1])) {
$new[] = $value." ".$array[$key+1];
$next_merge = $array[$key+1];
} else {
$new[] = $value;
}
}
print_r($new);
<pre>
You need to skip the iteration for the values that you have already added.
$array = ['coke.', 'fanta.', 'chocolate.'];
$cont = false;
foreach ($array as $key => $value) {
if ($cont) {
$cont = false;
continue;
}
if (strlen($value) < 6 && isset($array[$key+1])) {
$new[] = $value.' '.$array[$key+1];
$cont = true;
}
else {
$new[] = $value;
}
}
print_r($new);
I have the following array:
$array = [
['2017-02-26', '2017-02-27'],
['2017-03-01'],
['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04'],
['2017-01-05', '2017-01-06', '2017-01-07']
];
I'm looking to loop into this array to have something like this:
// When several dates
From 2017-02-26 to 2017-02-27.
// When only one date
On the 2017-03-01.
What I tried:
foreach ($array as $key => $value) {
$count = count($array[$key]);
if($count==1) {
echo "On the $key[$value]";
}
else {
$first = reset($array);
$last = end($array);
echo "From ".$first." to ".$last.;
}
}
But it doesn't work when there is only one date in the row.
You are looping by foreach() so it will display last echo string .Store result to one variable Eg($display) will be more easy to display that
$display = "";
foreach ($array as $key => $value) {
$count = count($array[$key]);
if($count==1) {
$display .= "On the $value[0] <br>";
}
else {
$first = $value[0];
$last = $value[$count-1];
$display .= "From ".$first." to ".$last."<br>";
}
}
echo $display;
Try this:-
foreach ($array as $key => $value) {
$count = count($value);
if($count==1) {
echo "On the ".$value[0];
}
else {
$first = reset($value);
$last = end($value);
echo "From ".$first." to ".$last;
}
}
Or just copy paste this code, it will work. Your main inside array to play with is $value.
I have array like this:
$array1 = array(Array('a','d'),
Array('c','a'),
Array('d','a'),
Array('a','b','c','d','e'),
);
$array2 = array(array('a','d'), array('a','b','c','d','e')) ;
$result = array();
Here's my code:
foreach ($array2 as $part) {
$key = implode(', ', $part);
if( ! array_key_exists ($key, $array1)) {
$result[$key] = 0;
}
$result[$key] = $result[$key] + 1;
}
foreach ($result as $key => $value) {
echo "$value of {$key}<br/>";
}
I want to count values $array2 based on $array1
I got this one:
1 of a,d
1 of a,b,c,d,e
But I want a result like this:
3 of a,d
1 of a,b,c,d,e
If anybody wonders why there's (3 of a,d), it count from array('a','d'), array('d','a') also counted as array('a','d') and array('a','b','c','d','e')
Try this. Here is a working demo https://eval.in/117810
<?
$array1 = array(array('a','d'),
array('c','a'),
array('d','a'),
array('a','b','c','d','e'),
);
$array2 = array(array('a','d'), array('a','b','c','d','e')) ;
$result = array();
foreach ($array2 as $key=>$part2) {
sort($part2);
if(!isset($result[$key]))$result[$key]=0;
foreach($array1 as $part1) {
$intersect = array_intersect($part1, $part2);
sort($intersect);
if ($intersect === $part2) {
$result[$key]++;
}
}
}
foreach($result as $k=>$v) {
echo $v . " of " . implode(',', $array2[$k]) . "<br/>";
}
?>