How to concatenate an array with a 'foreach' loop? - php

I have several arrays.
example:
$a = Array(
[0] => #ID_1
[1] => #ID_2
[2] => #ID_3
)
$b = Array(
[0] => ABC
[1] => cde
[2] => fgh
)
$c = Array(
[0] => 000
[1] => 111
[2] => 222
)
How to concatenate these data fields using any foreach, for, while loop?
Expected result:
$result = '#ID_1 ABC 000';
I try something like this:
$result = '';
foreach($a as $aa) {
$result .= $aa ." ";
foreach ($b as $bb) {
$result .= $bb ." ";
foreach($c as $cc) {
$result .= $cc .'<br>';
}
}
}
but the result did not meet expectations.
Can anyone advise how to use foreach to chain these arrays together? Thank you. Thank you very much.

If you need foreach loop then use next code:
$res = [];
foreach($a as $ind=>$val){
$res[$ind] = $val." ".$b[$ind]." ".$c[$ind];
}
Demo

You can do something like this.
$arr1 = ["#ID_1", "#ID_2", "#ID_3"];
$arr2 = ["ABC", "DEF", "FGH"];
$arr3 = ["000", "111", "222"];
$arrayLength = count($arr1);
$i = 0;
$result = [];
while ($i < $arrayLength)
{
$result[] = $arr1[$i]." ".$arr2[$i]." ".$arr3[$i];
$i++;
}
foreach($result as $item){
echo $item."<br/>";
}

According to what you're asking, you want to join elements with the key 0 from all arrays, then with the key 1 and so on, so instead of doing a foreach loop you could use a for loop using the key:
<?php
$a = Array(
0 => "#ID_1",
1 => "#ID_2",
2 => "#ID_3",
);
$b = Array(
0 => "ABC",
1 => "cde",
2 => "fgh"
);
$c = Array(
0 => 000,
1 => 111,
2 => 222
);
$length = sizeof($a);
$output = '';
for($i = 0; $i<$length; $i++) {
$output .= $a[$i] . ' / ' . $b[$i] . ' / ' . $c[$i] . '<br>';
}
echo $output;
?>
Outputs:
#ID_1 / ABC / 0
#ID_2 / cde / 111
#ID_3 / fgh / 222

Way to do this using foreach, if number of elements in each array is same.
$arr1 = ["#ID_1", "#ID_2", "#ID_3"];
$arr2 = ["ABC", "DEF", "FGH"];
$arr3 = ["000", "111", "222"];
foreach($arr1 as $k => $item) {
echo "$item {$arr2[$k]} {$arr3[$k]}<br>";
}

using for loop this way would give you your expected result
<?php
$a = Array(
0 => '#ID_1',
1 => '#ID_2',
2 => '#ID_3'
);
$b = Array(
0 => 'ABC',
1 => 'cde',
2 => 'fgh'
);
$c = Array(
0 => '000',
1 => '111',
2 => '222'
);
$arrlengtha = count($a);
$arrla = $arrlengtha - 2;
$arrlengthb = count($b);
$arrlb = $arrlengthb - 2;
$arrlengthc = count($c);
$arrlc = $arrlengthc - 2;
for($x = 0; $x < $arrla; $x++) {
echo $a[$x]." ";
}
for($x = 0; $x < $arrlb; $x++) {
echo $b[$x]." ";
}
for($x = 0; $x < $arrlc; $x++) {
echo $c[$x]." ";
}
?>

Related

Convert array to another character [php]

I have data in the form:
$data = Array ( [0] => 1 [1] => 4 [2] => 3 [3] => 3 )
I want to convert it to:
$x = [[1], [2], [3], [4]];
I do not know how to do this?
I'm using the library PHP-ML ( http://php-ml.readthedocs.io/en/latest/machine-learning/regression/least-squares/ ).
If you want to create array from values, you can do it this way:
$x = [];
foreach($data as $key => $value) {
array_push($x, $value);
}
If you want to create array of arrays from values you can edit it like this:
$x = [];
foreach($data as $key => $value) {
array_push($x, [$value]);
}
$data = array(1,4,3,3);
$x = '[['.implode('], [', $data).']]';
echo $x;
$data = array(0 => "0", 1 => "1", 2 => "2", 3 => "3");
$output;
$halt = count($data) - 1;
for($i = 0; $i < count($data); $i++){
if($i==$halt){
$output.="[".$data[$i]."]";
}else{
$output.="[".$data[$i]."]".", ";
}
}
$x = "[".$output."]";
echo $x;
Like so?
But why change array to array?
Ahhh I see, You want it in a json format?*
$array = array( 0 => [1], 1 => [2] , 2 => [3], 3 => [3] );
$x = json_encode($array, JSON_HEX_APOS);
echo $x;
[[1],[2],[3],[3]]

How to split the string in two arrays in Php

I have one array like this :
$array='{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1},{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}'
I want first split to two array like this :
$array[0]={b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1}
And
$array[1]={b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}
I change every array with this code
foreach ($b as $k => $m) {
if ($k % 2 == 0) {
$even[]= $m;
}
else {
$odd[] = $m;
}
}
$ff=array_combine($even,$odd);
I want output change like this
Array( Array[0] => ([b_price] => 9500 [b_discount] => 10 [mainPrice] => 95000 [total] => 95000 [title] =>obj1)
Array[1] => ([b_price] => 1500 [b_discount] => 15 [mainPrice] => 15000 [total] => 22500 [title] => obj2))
Two approaches:
-- using explode and array_map functions:
$str = '{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1},{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}';
$result = array_map(function($v){
$r = [];
$arr = explode(',', trim($v, '{}'));
foreach ($arr as $k => $v) {
if (!($k % 2)) $r[$v] = $arr[$k+1];
}
return $r;
}, explode('},{', $str));
print_r($result);
-- using additional preg_match_all and array_combine functions:
$str = '{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1},{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}';
$result = array_map(function($v){
preg_match_all('/([^,]+),([^,]+),?/', trim($v, '{}'), $m);
return array_combine($m[1], $m[2]);
}, explode('},{', $str));
print_r($result);
The output:
Array
(
[0] => Array
(
[b_price] => 9500
[b_discount] => 10
[mainPrice] => 95000
[total] => 95000
[title] => obj1
)
[1] => Array
(
[b_price] => 1500
[b_discount] => 15
[mainPrice] => 15000
[total] => 22500
[title] => obj2
)
)
you should change your needle, in your array string,
i have changed it with semicolon,
$arrayString='{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1};{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}';
echo $arrayString;
echo "<pre>"; print_r (explode(";",$arrayString));
$b=explode(";",$arrayString);
foreach ($b as $k => $m) {
if ($k % 2 == 0) {
$even[]= $m;
}
else {
$odd[] = $m;
}
}
$ff=array_combine($even,$odd);
So, I write this decision. Maybe it can be more clear, but it works.
$array='{b_price,9500,b_discount,10,mainPrice,95000,total,95000,title,obj1},{b_price,1500,b_discount,15,mainPrice,15000,total,22500,title,obj2}';
/*Making array from string*/
$tmp_array = explode("},{", $array);
/*Removing { symbols*/
$tmp_array[0] = substr($tmp_array[0],1);
$tmp_array[1] = substr($tmp_array[1],0,-1);
/*Making arrays from string [0] and [1]*/
$tmp_array[0] = explode(',',$tmp_array[0]);
$tmp_array[1] = explode(',',$tmp_array[1]);
$new_array = [];
/*Creating associative arrays*/
for($a = 0; $a < count($tmp_array); $a++) {
$new_as_array = [];
for($i = 0; $i <= count($tmp_array[0]); $i+=2) {
if($i + 1 <= count($tmp_array[0])) {
$new_as_array[$tmp_array[$a][$i]] = $tmp_array[$a][$i + 1];
}
}
$new_array[] = $new_as_array;
}
print_r($new_array);

Count array values in a loop and then add together

I'm struggling with this for a while now and getting more important at the moment.
Lets say we have a array with the values
Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
)
when i loop this array in a foreach loop i want the first result 11 second result 36 (11 + 25) 3rd result 38 (11 + 25 + 2) 4rd result 45 (11 + 25 + 2 +7) etc....
this way i get cumulative results
This is what i tried so far:
<?php
foreach(array_slice(weeks($start_week), 0, 26) as $week):
$gewasregistratie["gezette_vruchten_cumulatief"][$week] = $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week] + $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week-1];
$gewasregistratie["gezette_vruchten_cumulatief"][$week] += $gewasregistratie["gezette_vruchten"][$row["kenmerk"]][$week];
endforeach;
foreach(array_slice(weeks($start_week), 0, 26) as $week):
echo "<td week='".$week."' class='part1'>".$gewasregistratie["gezette_vruchten_cumulatief"][$week]."</td>";
endforeach;
foreach(array_slice(weeks($start_week), 26, 51) as $week):
echo "<td week='".$week."' class='part2'>".$gewasregistratie["gezette_vruchten_cumulatief"][$week]."</td>";
endforeach;
?>
Can someone help me in the right direction ?
Simple like boiling a egg. Try this code
$test = array(11,25,2,7);
$count = 0;
foreach($test as $i=>$k)
{
$count +=$k;
echo $count." ";
}
Output:
11 36 38 45
Suggestion: you can store output in another array also.
Try this:
$a = array(11,25,2,7);
$c = 0;
foreach($a as $k=>$v){
$c += $v;
$b[] = $c;
}
print_r($b);
you will get result in array like below :
Array ( [0] => 11 [1] => 36 [2] => 38 [3] => 45 )
The simplest way
$original = array(23, 18, 5, 8, 10, 16);
$total = array();
$runningSum = 0;
foreach ($original as $number) {
$runningSum += $number;
$total[] = $runningSum;
}
var_dump($total);
$array = array( 11, 25, 2, 7 );
$results = array();
foreach ($array AS $i => $v) {
if (empty($results)) {
$results[] = $v;
} else {
$results[] = $v + $results[$i - 1];
}
}
Something like this.
Try this code
$arr=Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
);
$sum=0;
foreach($arr as $k=>$val)
{
echo "<br>".$sum+=$val;
}
Find below solution
$arr = array(11,25,2,7);
$sum =0;
foreach($arr as $val){
$sum +=$val;
echo $sum ."<br/>";
}
If you are looking to iterate over a single-dimensional array as your question was initially worded, array_map would be your most efficient method:
function cascade($n) {
static $current = 0;
return $current += (int) $n;
}
$test = array(11,25,2,7);
$result = array_map('cascade', $test);
/**
* You could also assign back to the original array like:
* $test = array_map('cascade', $test);
*/
If you are looking to do something in a multi-dimensional array, using array_walk would be the solution there. Would you like an example?
Try this.
$myArray = Array
(
[0] => 11
[1] => 25
[2] => 2
[3] => 7
);
$total = 0;
for($i=1; $i <= count($myArray); $i++) {
$total += $myArray[$i];
echo $total . ", ";
$cumulativeArray[] = $total;
}
print_r($cumulativeArray);

combine arrays and concat value?

Little complex to explain , so here is simple concrete exemple :
array 1 :
Array
(
[4] => bim
[5] => pow
[6] => foo
)
array 2 :
Array
(
[n] => Array
(
[0] => 1
)
[m] => Array
(
[0] => 1
[1] => 2
)
[l] => Array
(
[0] => 1
[1] => 4
[2] => 64
)
And i need to output an array 3 ,
array expected :
Array
(
[bim] => n-1
[pow] => Array
(
[0] => m-1
[1] => m-2
)
[foo] => Array
(
[0] => l-1
[1] => l-4
[2] => l-64
)
Final echoing OUTPUT expected:
bim n-1 , pow m-1 m-2 ,foo l-1 l-4 l-64 ,
I tried this but seems pity:
foreach($array2 as $k1 =>$v1){
foreach($array2[$k1] as $k => $v){
$k[] = $k1.'_'.$v);
}
foreach($array1 as $res =>$val){
$val = $array2;
}
Thanks for helps,
Jess
CHALLENGE ACCEPTED
<?php
$a = array(
4 => 'bim',
5 => 'pow',
6 => 'foo',
);
$b = array(
'n' => array(1),
'm' => array(1, 2),
'l' => array(1, 4, 64),
);
$len = count($a);
$result = array();
$aVals = array_values($a);
$bKeys = array_keys($b);
$bVals = array_values($b);
for ($i = 0; $i < $len; $i++) {
$combined = array();
$key = $aVals[$i];
$prefix = $bKeys[$i];
$items = $bVals[$i];
foreach ($items as $item) {
$combined[] = sprintf('%s-%d', $prefix, $item);
};
if (count($combined) === 1) {
$combined = $combined[0];
}
$result[$key] = $combined;
}
var_dump($result);
?>
Your code may be very easy. For example, assuming arrays:
$one = Array
(
4 => 'bim',
5 => 'pow',
6 => 'foo'
);
$two = Array
(
'n' => Array
(
0 => 1
),
'm' => Array
(
0 => 1,
1 => 2
),
'l' => Array
(
0 => 1,
1 => 4,
2 => 64
)
);
You may get your result with:
$result = [];
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$result[$oneValue] = array_map(function($item) use ($twoKey)
{
return $twoKey.'-'.$item;
}, $twoValue);
};
-check this demo Note, that code above will not make single-element array as single element. If that is needed, just add:
$result = array_map(function($item)
{
return count($item)>1?$item:array_shift($item);
}, $result);
Version of this solution for PHP4>=4.3, PHP5>=5.0 you can find here
Update: if you need only string, then use this (cross-version):
$result = array();
while((list($oneKey, $oneValue) = each($one)) &&
(list($twoKey, $twoValue) = each($two)))
{
$temp = array();
foreach($twoValue as $item)
{
$temp[] = $twoKey.'-'.$item;
}
$result[] = $oneValue.' '.join(' ', $temp);
};
$result = join(' ', $result);
As a solution to your problem please try executing following code snippet
<?php
$a=array(4=>'bim',5=>'pow',6=>'foo');
$b=array('n'=>array(1),'m'=>array(1,2),'l'=>array(1,4,64));
$keys=array_values($a);
$values=array();
foreach($b as $key=>$value)
{
if(is_array($value) && !empty($value))
{
foreach($value as $k=>$val)
{
if($key=='n')
{
$values[$key]=$key.'-'.$val;
}
else
{
$values[$key][]=$key.'-'.$val;
}
}
}
}
$result=array_combine($keys,$values);
echo '<pre>';
print_r($result);
?>
The logic behind should be clear by reading the code comments.
Here's a demo # PHPFiddle.
//omitted array declarations
$output = array();
//variables to shorten things in the loop
$val1 = array_values($array1);
$keys2 = array_keys($array2);
$vals2 = array_values($array2);
//iterating over each element of the first array
for($i = 0; $i < count($array1); $i++) {
//if the second array has multiple values at the same index
//as the first array things will be handled differently
if(count($vals2[$i]) > 1) {
$tempArr = array();
//iterating over each element of the second array
//at the specified index
foreach($vals2[$i] as $val) {
//we push each element into the temporary array
//(in the form of "keyOfArray2-value"
array_push($tempArr, $keys2[$i] . "-" . $val);
}
//finally assign it to our output array
$output[$val1[$i]] = $tempArr;
} else {
//when there is only one sub-element in array2
//we can assign the output directly, as you don't want an array in this case
$output[$val1[$i]] = $keys2[$i] . "-" . $vals2[$i][0];
}
}
var_dump($output);
Output:
Array (
["bim"]=> "n-1"
["pow"]=> Array (
[0]=> "m-1"
[1]=> "m-2"
)
["foo"]=> Array (
[0]=> "l-1"
[1]=> "l-4"
[2]=> "l-64"
)
)
Concerning your final output you may do something like
$final = "";
//$output can be obtained by any method of the other answers,
//not just with the method i posted above
foreach($output as $key=>$value) {
$final .= $key . " ";
if(count($value) > 1) {
$final .= implode($value, " ") .", ";
} else {
$final .= $value . ", ";
}
}
$final = rtrim($final, ", ");
This will echo bim n-1, pow m-1 m-2, foo l-1 l-4 l-64.

Counting the number of letters in a word by PHP

I want to create an array which has two columns. The output should contain only the existing letters in the word with their amounts.
The wanted output of the following code
a 3
s 2
p 1
What is wrong in the following PHP code?
<?php
$alpha = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','z','y');
$word = "saapas";
for ( $i = 0; $i < count($word); $i++ ) {
echo $word[$i] . "\n";
$table[$word[$i]][]++; // Problem here
}
// array_unique, array_combine and some method which can sort arrays by alphabets can be useful
PHP has extensive array functions that do much of the heavy lifting for this:
$keys = range('a', 'z');
$values = array_fill(0, 26, 0);
$freq = array_combine($keys, $values);
$word = "saapas";
$len = strlen($word);
for ($i=0; $i<$len; $i++) {
$letter = strtolower($word[$i]);
if (array_key_exists($letter, $freq)) {
$freq[$letter]++;
}
}
print_r($freq);
Output:
Array
(
[a] => 3
[b] => 0
[c] => 0
[d] => 0
[e] => 0
[f] => 0
[g] => 0
[h] => 0
[i] => 0
[j] => 0
[k] => 0
[l] => 0
[m] => 0
[n] => 0
[o] => 0
[p] => 1
[q] => 0
[r] => 0
[s] => 2
[t] => 0
[u] => 0
[v] => 0
[w] => 0
[x] => 0
[y] => 0
[z] => 0
)
If you want to distinguish between uppercase and lowercase try:
$keys = array_merge(range('a', 'z'), range('A', 'Z'));
$values = array_fill(0, 52, 0);
$freq = array_combine($keys, $values);
$word = "saApas";
$len = strlen($word);
for ($i=0; $i<$len; $i++) {
$letter = $word[$i];
if (array_key_exists($letter, $freq)) {
$freq[$letter]++;
}
}
print_r($freq);
Or to count any characters:
$freq = array();
$word = "saApas";
$len = strlen($word);
for ($i=0; $i<$len; $i++) {
$letter = $word[$i];
if (array_key_exists($letter, $freq)) {
$freq[$letter]++;
} else {
$freq[$letter] = 1;
}
}
print_r($freq);
This works using your input characters array, but do you really want to build a static array for this task?
$table = array();
$count = strlen($word);
for ( $i = 0; $i < $count; $i++ ) {
$letter = $word[$i];
if ( !isset($table[$letter]) )
{
$table[$letter] = 0;
}
++$table[$letter];
}
Here's a method of doing the same thing, but utilizing PHP's native functions:
$ascii = count_chars($word, 1);
$keys = array_keys($ascii);
$chars = array_map('chr', $keys);
$charCount = array_values($ascii);
$table = array_combine($chars, $charCount);
Why complicate?
$string = 'the grey fox jumps over the lazy dog';
$words = explode(' ', $string);
foreach ($words as $key => $value)
{
$words[$key] = count_chars($value, 1);
}
echo '<pre>';
print_r($words);
echo '</pre>';
for ( $i = 0; $i < $alpha.length; $i++ ) {
$count = 0;
for($a = 0; $a < count($word); $a++)
{
if($word[$a] == $array[$i]
$count++;
}
if($count > 0)
echo $array[$i] . " " . $count . "\n";
}
So we use 2 for loops. A little inefficient that what your trying to do. One to check for each character of the alphabet. The second loop is to loop through the string and count the matches against the alphabet the first loop is on.
Edit:
Or you could add a zero to the line below and remove the echo from the loop. Which still requires another loop to display this table.
$table[$word[$i]][0]++;
try this out.it is a single iteration method and faster and simple!
<?php
$word = "saapas";
$result;
for ( $i = 0; $i < strlen($word); $i++ ) {
echo $word[$i] . "\n";
$result[$word[$i]]++; //make use of associative arrays to store the count for each alphabet.
}
foreach($result as $key => $value)//print each element inside the result array
{
print $key . " = " . $value . "<br />";
}
?>
count() doesn't quite work that way, you have to explicitly convert to an array if you want to use the count function. As for the $table array, you have an extra dimension (the []).
The following code should work (it is not optimal but should get you pointed in the right direction.)
$word = str_split("saapas");
for ( $i = 0; $i < count($word); $i++ ) {
$table[$word[$i]]++;
}
foreach ($table as $key => $value) {
print "$key $value\n";
}

Categories