Question
Currently My output is coming like this PNL testing 1,10,PNL testing 2,55, I want to manipulate it and store it in two different variables as a string like:
$teams = "PNL testing 1, PNL testing 2";
$amount = "10, 55";
Please let me know how should I split in the above format.
Code
while ($row1 = mysql_fetch_assoc($result)){
$profit = 0;
$total = 0;
$loss = 0;
$final_array = '';
$final_array .= $teams = $row1['t_name'].",";
$teams = explode(",", $teams);
$transact_money = $row1['pnl_amount'];
$pnl_results = $row1['pnl'];
$transact_money = explode("|", $transact_money);
$pnl_results = explode("|", $pnl_results);
for($i=0; $i<count($transact_money); $i++){
if($pnl_results[$i]=='Profit'){
$profit = $profit + $transact_money[$i];
}else{
$loss = $loss + $transact_money[$i];
}//end if
}//end for..
$team_profits = $profit - $loss.",";
$final_array .= $team_profits;
echo $final_array;
}
$s = "PNL testing 1,10,PNL testing 2,55";
$res = array();
$result = preg_match_all("{([\w\s\d]+),(\d+)}", $s, $res);
$teams = join(', ', $res[1]); //will be "PNL testing 1, PNL testing 2"
$amount = join(', ', $res[2]); //will be "10, 55"
$string = "PNL testing 1,10,PNL testing 2,55,";
preg_match_all("/(PNL testing \d+),(\d+),/", $string, $result);
$teams = implode(",", $result[1]);
$amount = implode(",", $result[2]);
Less fancy than RegExp, but more obvious:
$final_array = "PNL testing 1,10,PNL testing 2,55";
$final_array_array = explode(',', $final_array);
$teams = array();
$amount = array();
$index = 0;
foreach ($final_array_array as $item) {
switch ($index) {
case 0:
$teams[] = $item;
break;
case 1:
$amount[] = $item;
}
$index = 1-$index;
}
Related
Hey i have array calculation where i need to refactor this code using loops please suggest...
<?php
arr = [286538,237034,192724,150815,117523,82754,49707];
$a1 = $arr[0]/7;
$a2 = ($a1+$arr[1])/7;
$a3 = ($a1+$a2+$arr[2])/7;
$a4 = ($a1+$a2+$a3+$arr[3])/7;
$a5 = ($a1+$a2+$a3+$a4+$arr[4])/7;
$a6 = ($a1+$a2+$a3+$a4+$a5+$arr[5])/7;
$a7 = ($a1+$a2+$a3+$a4+$a5+$a6+$arr[6])/7;
?>
Output -
40934
39709.714285714
39052.530612245
38644.463556851
39409.10120783
40071.972808949
41075.540353084
Here is how you can utilize loops in your problem:
$arr = [286538,237034,192724,150815,117523,82754,49707];
$newArr = [];
$counter = 0;
while($counter < count($arr)){
$sum = array_sum($newArr);
$newArr[] = ($sum + $arr[$counter]) / 7;
$counter++;
}
<?php
$arr = [286538,237034,192724,150815,117523,82754,49707];
function calcarr($n){
$result = 0;
global $arr;
if ($n <= 0) return $result;
for ($i=0;$i<$n;$i++) $result += calcarr($i);
return ($result + $arr[$n-1])/7;
}
$a1 = $arr[0]/7;
$a2 = ($a1+$arr[1])/7;
$a3 = ($a1+$a2+$arr[2])/7;
$a4 = ($a1+$a2+$a3+$arr[3])/7;
$a5 = ($a1+$a2+$a3+$a4+$arr[4])/7;
$a6 = ($a1+$a2+$a3+$a4+$a5+$arr[5])/7;
$a7 = ($a1+$a2+$a3+$a4+$a5+$a6+$arr[6])/7;
echo "$a7\n";
echo calcarr(7)."\n";
?>
RESULT:
41075.540353084
41075.540353084
<?php
$arr = [286538,237034,192724,150815,117523,82754,49707];
$result = [];
foreach($arr as $k => $item)
$result["a$k"] = (float) (array_sum($result) + $item)/7;
var_dump($result);
Output:
array(7) {
["a0"]=>
float(40934)
["a1"]=>
float(39709.714285714)
["a2"]=>
float(39052.530612245)
["a3"]=>
float(38644.463556851)
["a4"]=>
float(39409.10120783)
["a5"]=>
float(40071.972808949)
["a6"]=>
float(41075.540353084)
}
If you want the variables as you have listed:
extract($result);
If you don't care about keys and to extract those variables, this will just give you a 0 indexed array as for your result:
foreach($arr as $item)
$result[] = (float) (array_sum($result) + $item)/7;
I have 2 arrays in php
$array1[] = a,b,c,d,e;
$array2[] = 1,2,3,4,5;
$data = array('letter'=>$array1,'num'=>$array2);
return json_encode($data);
This will return:
[[a,b,c,d,e],[1,2,3,4,5]]
I'd like to return it in json_encode like this:
$data = [[1a,1],[b,2],[c,3],[d,4],[e,5]];
Can someone help me with this?
this is the simplest solution
$result = array();
foreach ($array1 as $k1 => $v1) {
$result[] = array($v1, $array2[$k1]);
}
echo json_encode($result)
but arrays must have the same length and same keys
Try below code, it is flexible and don't have to care about the length of the arrays.
<?php
$letters = array('a','b','c','d','e');
$numbers = array('1','2','3','4','5');
$counter = (sizeof($letters) > sizeof($numbers)) ? sizeof($letters) : sizeof($numbers);
$arr = array();
for($i=0; $i<$counter; $i++)
{
if(array_key_exists($i, $letters))
$arr[$i][] = $letters[$i];
if(array_key_exists($i, $numbers))
$arr[$i][] = $numbers[$i];
}
$json = json_encode($arr);
echo $json;
Output:
[["a","1"],["b","2"],["c","3"],["d","4"],["e","5"]]
Demo:
http://3v4l.org/7v7X4
What you are looking for is the function array_combine().
Here is an example:
$array1 = array("a","b","c","d","e");
$array2 = array(1,2,3,4,5);
$data = array_combine($array1, $array2);
$new_data = array();
foreach($data AS $key => $value) {
$new_data[] = array($key, $value);
}
print_r(json_encode($new_data));
Which should return something like:
[["a",1],["b",2],["c",3],["d",4],["e",5]]
UPDATE Changed the code to give the result wanted...
I'm using the below code to separate odd and even and store it in different variable. When there are only 2 value available then it works fine but when the number value increases then it doesn't. I want to make it dynamic so that n number of values can be separated and stored correctly.
Example:
If the value of
$final_array = "PNL testing 1,10,PNL testing 2,35,";
It prints nicely:
$teams = "PNL testing 1, PNL testing 2";
$amount = "10, 35";
But when it increases from
$final_array = "PNL testing 1,10,PNL testing 2,35,";
to
$final_array = "PNL testing 1,10,PNL testing 2,35,Team 3,95,";
Then also it prints
$teams = "PNL testing 1, PNL testing 2";
$amount = "10, 35";
Please guide me through on where I am going wrong.
$res = array();
$result = preg_match_all("{([\w\s\d]+),(\d+)}", $final_array, $res);
$teams = join(', ', $res[1]); //will display teams
$amount = join(', ', $res[2]); //will display amount every team have
echo $teams . "<br />" . $amount;
I think you can totally drop the REGEX in favor of good old explode/implode with some logic in it:
$teams = array();
$amount = array();
$a = explode(',', trim(trim($final_array), ','));
foreach ($a as $i => $v)
if (($i % 2) == 0) $teams[] = trim($a);
else $amount[] = trim($a);
$teams = implode(', ', $teams);
$amount = impode(', ', $amount);
In the above code $tms and $amn are temporary arrays. In the foreach we take the exploded values from the string and we store them in those two arrays sorting them by key (if it's even then it's a team otherwise it's an amount).
At the end we just implode the new values into your output variables $teams and $amount.
It will much easier I think to use explode:
$result = explode(',', $final_array);
$teams = array();
$amount = array();
foreach ($result as $key => $value) {
if ($key % 2 == 0) {
$teams[] = $value;
} else {
$amount[] = $value;
}
}
$teams = implode(', ', $teams); //will display teams
$amount = implode(', ', $amount); //will display amount every team have
echo $teams."<br />".$amount;
I would change this part of Michal Trojanowski for more efficiency
foreach ($result as $key => $value) {
if ($key % 2 == 0) {
$teams[] = $value;
} else {
$amount[] = $value;
}
}
you see it has an extra condition we can remove it by like this
$length = count($result);//cache count result
for ($i = 0; $i < $length; $i += 2) {
$teams[] = $result[$i];
}
for ($i = 1; $i < $length; $i += 2) {
$amount[] = $result[$i];
}
Here the loop is running same but it just removes the the condition.
I've got field in my database which contain strings like 21;48;33;22;31. Then I'd like to convert it to mathematical calculation 21+48+33+22+31.
$points = "21;48;33;22;31";
$points = str_replace(";","+",$points );
$points = preg_replace('/[^0-9\+\-\*\/\s]+/', '', $points);
echo $points;
But that simply does not work. I've got the same string "21+48+33+22+31" instead of the sum.
$points = "21;48;33;22;31";
$points = explode(';',$points );
$points = array_sum($points);
echo $points;
$points = "21;48;33;22;31";
$arr = explode(";", $points);
$points = 0;
foreach($arr as $key => $rows){
$points += $rows[$key];
}
echo $points;
Try above code it will give you proper result.
or you can try it also:
$points = "21;48;33;22;31";
$arr = explode(";", $points);
echo $points = array_sum($arr);
The easiest way is to explode the string.
Then you can iterate with foreach over the resulting array and calculate them.
$points = "21;48;33;22;31";
$points = explode(";", $points);
$calc = 0;
forearch($points as $point) {
$calc += $point;
}
Or your can use array_sum:
$points = "21;48;33;22;31";
$points = explode(";", $points);
$calc = array_sum($points);
Something like that. Perhaps there are some shorter ways.
$string = "21;48;33;22;31";
$string = explode(";" , "21;48;33;22;31");
$point = 0;
foreach($string as $num)
{ // by using (int) you can convert string to int.
$point = (int)$num + $point;
}
print($point);
// output
155
explode it then loop for sum...
<?php
$total = 0; // for getting the total
$points = "21;48;33;22;31";
$points = explode(';',$points);
for($i=0;$i<count($points);$i++){
$total+= $points[$i];
}
echo $total;
?>
<?php
eval('$sum = ' . str_replace(';','+','21;48;33;22;31').';');
echo $sum;
Using PHP, let's say I have this string:
$letters = "abcde";
I would like to add the character "7" between every character, but so it only occurs once. The result should be an array as follows:
$lettersArray = array(
7abcde,
a7bcde,
ab7cde,
abc7de,
abcd7e,
abcde7
);
Note: the length of $letters is dynamic from 1 to 12 characters
I have tried using loops with array_splice and str_split with implode, but I can't quite figure out the right logic.
It is very simple , do like this
echo implode("+", str_split('vimal')); // OUTPUT : v+i+m+a+l
Have a nice day
Try this:
$letters ='abcdefghi';
$lettersArray = array();
for($i=0;$i < strlen($letters)+1; $i++) {
$new = substr($letters, 0, $i);
$new .= '7';
$new .= substr($letters, $i);
$lettersArray[] = $new;
}
print_r($lettersArray);
What this does is take each element of the array, and inserts the letter 7 in an incrementing fashion into the array item.
$split_letters = str_split($letters);
$letters_array = array();
for($i = 0; $i <= count($split_letters); $i++) {
$start_letters = array_slice($split_letters, 0, $i);
$end_letters = array_slice($split_letters, $i);
$letters_array[] = array_merge($start_letters, array(7), $end_letters);
}
After 2 hours (including writing this question) I finally also came up with a solution that is similar to the others posted here. It's posted below, but I prefer other solutions posted here.
$letters = "abcde";
$results = array();
$lettersArray = str_split($letters);
foreach ($lettersArray as $key => $lets) {
$tempArray = $lettersArray;
array_splice($tempArray, $key, 0, "7");
$results[] = implode($tempArray);
}
$results[] = $letters . "7"; //required for the final combination
print_r($results);
Try this
$letters = "abcde";
$character = "7";
$len = strlen($letters);
$lettersArray = array();
for($i=0; $i <= $len; $i++)
{
$temp = "";
$temp = substr($letters, 0, $i) . $character . substr($letters, $i);
$lettersArray[] = $temp;
}
http://codepad.viper-7.com/gFByJb