Issue with summing arrays PHP - php

I'm trying to turn MySQL data into an array and then calculate the sum of that array.
$weight = ($product['av_id_1'])*$val; // get attribute values
$weightsub = explode(" ", $weight); // convert string to array
echo array_sum($weightsub);
I'm getting an output but its not what I expected, instead of a single integer its spaced integers like "30 40 50".
Where am I going wrong?
Thanks

$weightsub = explode(" ", $product['av_id_1']); // convert string to array
echo array_sum($weightsub)*$val;
First you need to extract all numbers using explode. Then apply array_sum to sum all numbers in the array, and multiply the sum by $val.
If this doesn't work as intended, you can easily do some basic debugging by using echo and print_r on each variable or result:
echo '$product[av_id_1] = <br>';
print_r($product['av_id_1']);
$weightsub = explode(" ", $product['av_id_1']); // convert string to array
echo '$weightsub = <br>';
print_r($weightsub);
echo "<br>\$val = $val<br>";
echo 'Sum = ' . array_sum($weightsub) . '<br>';
echo array_sum($weightsub)*$val;

Related

How to count and display array values in php

I have one object array data coming below way.
$rooms= Single room,Single room,Single room ;
Here i want to display data below format
3 X Single room
For example rooms coming below format
Single room, Double room , Single room
then i need to out put is
2x single room
1x Double room
How to get like this ,Please tell me, i tried array_count_values and array_unique but not get result. Please any one know tell me
$str = rtrim(implode(",",explode("#", Single Room#DOuble Room#Single Room)));
$ss= str_replace(' ','',$str);
$ss1= str_replace(',',' ',$ss);
$rooms = explode(' ', $ss1);
//Count each occurence of values
$countedValues = array_count_values($rooms);
//Build strings from value and display them.
foreach( $countedValues as $roomType=>$count ){
echo $count . 'x ' . $roomType . '<br />';
}
I don't know how you're using array_count_values because you haven't posted your code, please post your code in future. Below is a working example that gives your desired output.
<?php
$rooms = "Single room,Single room,Single room,Double room";
$rooms = explode(',', $rooms); // array of rooms
//Count each occurence of values
$countedValues = array_count_values($rooms);
//Build strings from value and display them.
foreach( $countedValues as $roomType=>$count ){
echo $count . 'x ' . $roomType . '<br />';
}
?>
This gave me the output:
3x Single room
1x Double room
Please note that your question includes this:
$rooms= Single room,Single room,Single room ;
this is not a valid array format. You should use this instead:
$rooms = array("Single room","Single room","Single room");

How to apply double quotes to each value in a comma-space delimited string?

I want to add double quotes of my every array.
Original value is:
192.168.183.2, 192.168.183.28
The current result is:
"192.168.183.2, 192.168.183.28"
What I want is:
"192.168.183.2", "192.168.183.28"
and here is my code:
$allowedIP = array($dScheduler['ALLOWED_IP_ADDRESS']);
echo $newarray='"'.implode('","', $allowedIP).'"';
Your input value is a string, so handle it with just one string function call (str_replace()):
Code: (Demo)
$dScheduler['ALLOWED_IP_ADDRESS']='192.168.183.2, 192.168.183.28'; // your input string
$wrapped='"'.str_replace(', ','", "',$dScheduler['ALLOWED_IP_ADDRESS']).'"';
echo $wrapped;
echo "\n\n";
// if you want an array:
$array=explode(', ',$wrapped); // generate result array
foreach($array as $v){
echo "$v\n";
}
The value delimiter in your input string is: ,, so you just need to change it to ", " and wrap the entire string in " as well.
Then you simply explode on the commas to generate your desired array of elements.
Output:
"192.168.183.2", "192.168.183.28"
"192.168.183.2"
"192.168.183.28"
Do it through a loop:
$new_array = array();
foreach($array as $a) {
$new_array[] = '"'.$a.'"';
}
It will create a new array with ", around each element.
You can use array_map
<?php
$allowedIP = array('192.168.183.2, 192.168.183.28');
$arrAllowedIP = explode(',', $allowedIP[0]);
$quotedIP = array_map(function($val)
{
return '"'.trim($val).'"';
}, $arrAllowedIP);
Try This,
$arr = ["192.168.183.2", "192.168.183.28"];
$imp = '"'.implode('", "', $arr).'"'; // to string with double quote
$exp = explode(',', $imp); // to array with double quote
echo $im;
print_r($exp);
$allowedIP = array('192.168.183.2, 192.168.183.28');
$new= implode($allowedIP);
$fl=',';
foreach (explode(',',$new) as $v){
echo '"'.$v.'"'.$fl;
$fl='';
};

PHP changing array format

I'm trying to change an array format from this
{"updated":"2016-01-28 02:00:02","rate":"0.1898"}
to this
[2016-01-28 02:00 , 0.1898]
I'm getting the first array format from a MySQL query and need to convert to the second format to use in a line chart.
$newVal = array();
foreach ($dbresult as $key => $value) {
$newVal[] = json_encode(array_values($value));
}
echo implode(",", $newVal);
With this new code block i get this format
["2016-01-28 02:00" , "0.1898"]
But still need to get rid of the double quotes, any ideas?
$json = '[{"updated":"2016-01-28 02:00:02","rate":"0.1898"}]';
echo json_encode(array_map(function ($data) {
return [$data->updated, $data->rate];
}, json_decode($json)));
In other words:
JSON-decode it
loop through it
create a new array with updated in the first index and rate in the second
JSON-encode it again
Step 3 is necessary since JSON objects don't guarantee any particular order, so relying on the decoded order of the keys is not reliable; and it also guarantees you get the data you want even if you add more keys to your objects.
Try this code
$string = ' {"updated":"2016-01-28 02:00:02","rate":"0.1898"}';
$array = json_decode($string, true);
$str = json_encode(array_values($array));
echo str_replace('"', '', $str);
you should try this
$str ='{"updated":"2016-01-28 02:00:02","rate":"0.1898"}';
$data=json_decode($str);
echo '<pre>';
echo 'json decode it returns ojbects<br>';
print_r($data);
echo 'convert object into array<br>';
$data=(array)$data;
print_r($data);
echo 'Your Output<br>';
echo json_encode(array_values($data));

Array values into string

I've been searching and searching and can't find anything that works, but this is what I want to do.
This code:
try{
$timeout = 2;
$scraper = new udptscraper($timeout);
$ret = $scraper->scrape('udp://tracker.openbittorrent.com:80',array('0D7EA7F06E07F56780D733F18F46DDBB826DCB65'));
print_r($ret);
}catch(ScraperException $e){
echo('Error: ' . $e->getMessage() . "<br />\n");
echo('Connection error: ' . ($e->isConnectionError() ? 'yes' : 'no') . "<br />\n");
}
Outputs this:
Array ( [0D7EA7F06E07F56780D733F18F46DDBB826DCB65] => Array ( [seeders] => 148 [completed] => 10 [leechers] => 20 [infohash] => 0D7EA7F06E07F56780D733F18F46DDBB826DCB65 ) )
And I want that seeder count into a string such as $seeds. How would I go about doing this?
Something like this?
$seeds = $ret['0D7EA7F06E07F56780D733F18F46DDBB826DCB65']['seeders'];
you can user strval() to convert a number to a string.
$string = strval($number);
or you can cast it into a string:
$string = (string)$number;
in your context that would be:
$string = strval($ret['0D7EA7F06E07F56780D733F18F46DDBB826DCB65']['seeders']);
However that odd string is also the first index of the array so you could also do it like this:
$string = strval($ret[0]['seeders']);
or if you want ot use only indexes ('seeders' is also the first index of the second array):
$string = strval($ret[0][0]);
if you just want the number then it's easy too:
$num = $ret[0][0];
It's not clear if you're looking to assign the array value(s?) as a separate variable(s?) or just to cast it into a string. Here's a nice way to accomplish all the above options, by assigning each array key as a separate variable with the matching array value:
$ret_vars = array_pop($ret);
foreach ($ret_vars as $variable_name=>$variable_value) :
${$variable_name} = (string)$variable_value;
endforeach;
In your original example, this would end up populating $seeders, $completed, $leechers and $infohash with their matching string values. Of course, make sure these variable names are not used/needed elsewhere in the code. If that's the case, simply add some sort of unique prefix to the ${} construct, like ${'ret_'.$variable_name}

PHP - Adding up an array of numbers?

I have a PHP script that returns an array of numbers:
$fh = fopen ("./files/".$file, r);
$filedata= explode('|', fgets($fh));
echo $filedata[5];
result:
0.23387718200684
3.6163940429688
0.030826568603516
Is there a way to get the script to return results added up as just one number?
echo array_sum($filedata);
I think that should do the trick.
Take a look here for further information. array_sum just sums up all the values in an array.
EDIT
The above example would work if your array was a flat array of integers, decimals etc. The following is how you would sum up a 2 dimensional array where the value you want to sum is at index position 5:
var $sum = 0;
foreach($filedata as $dataElement) {
$sum += $dataElement[5];
}
echo $sum;
The above code assume that $filedata is an array of array's, each array in filedata has a value at index 5 that can be summed up... Is that more along the lines of what you need?
You could use array_sum:
echo array_sum($filedata);
Not working?
As might be your case $filedata[5] actually contains a string with newlines and numbers. In this case you need some extra code. Important is the line endings - these can be different depending on your operating system / file.
$sum = 0;
$sLineEnding = "\r\n";
foreach($filedata as $data)
{
$parts = explode($sLineEnding, $data);
$sum += array_sum($parts);
}
echo $sum;
As I see in your code, you are executing it in command line and you do echo $filedata[5] an you get different lines, this is because you are not paying attention to '\n' character, so what you need is to change that character somehow...
there are different ways... In this example I'm changing the "\n" for " " simple space
$fh = fopen ("./files/".$file, r);
$filedata= explode('|', fgets($fh));
// if "\n" is not working try '\n'
// One way
echo str_replace(" ","\n",$filedata[5]);
// Another way
echo implode(" ", explode("\n", $filedata[5]));

Categories