how to remove the array to string conversion error in php - php

i am working on php i have dynamic array i need to get the array result store in some variable i encounter the error :array to string conversion
coding
<?php
require_once('ag.php');
class H
{
var $Voltage;
var $Number;
var $Duration;
function H($Voltage=0,$Number=0,$Duration=0)
{
$this->Voltage = $Voltage;
$this->Number = $Number;
$this->Duration = $Duration;
}}
//This will be the crossover function. Is just the average of all properties.
function avg($a,$b) {
return round(($a*2+$b*2)/2);
}
//This will be the mutation function. Just increments the property.
function inc($x)
{
return $x+1*2;
}
//This will be the fitness function. Is just the sum of all properties.
function debug($x)
{
echo "<pre style='border: 1px solid black'>";
print_r($x);
echo '</pre>';
}
//This will be the fitness function. Is just the sum of all properties.
function total($obj)
{
return $obj->Voltage*(-2) + $obj->Number*2 + $obj->Duration*1;
}
$asma=array();
for($i=0;$i<$row_count;$i++)
{
$adam = new H($fa1[$i],$fb1[$i],$fcc1[$i]);
$eve = new H($fe1[$i],$ff1[$i],$fg1[$i]);
$eve1 = new H($fi1[$i],$fj1[$i],$fk1[$i]);
$ga = new GA();
echo "Input";
$ga->population = array($adam,$eve,$eve1);
debug($ga->population);
$ga->fitness_function = 'total'; //Uses the 'total' function as fitness function
$ga->num_couples = 5; //4 couples per generation (when possible)
$ga->death_rate = 0; //No kills per generation
$ga->generations = 10; //Executes 100 generations
$ga->crossover_functions = 'avg'; //Uses the 'avg' function as crossover function
$ga->mutation_function = 'inc'; //Uses the 'inc' function as mutation function
$ga->mutation_rate = 20; //10% mutation rate
$ga->evolve(); //Run
echo "BEST SELECTED POPULATION";
debug(GA::select($ga->population,'total',3)); //The best
$array=array((GA::select($ga->population,'total',3))); //The best }
?>
<?php
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone
?
>
i apply implode function but its not working
it display the error of : Array to string conversion in C:\wamp\www\EMS3\ge.php on line 146 at line $r=implode($rt,",");

<script>
if ( ($textboxB.val)==31.41)
{
</script>
<?php echo "as,dll;g;h;'islamabad"; ?>
<script>} </script>
You are running your java script code in PHP, I havent implemented your code just checked and found this bug.You can get the value by submitting the form also
---------------------------- Answer For your Second updated question------------------------
<?php
$array = array(
"name" => "John",
"surname" => "Doe",
"email" => "j.doe#intelligence.gov"
);
$comma_separated = implode(",", $array); // You can implode them with any character like i did with ,
echo $comma_separated; // lastname,email,phone
?>

Related

Getting variable from one function and pass to another in PHP

I have a functiona within a function. Function B gets a value from an API and passes it to function A. However, when I echo the value within Function B it works but it is null when called in function A.
Should I be storing the value in a session variable or DB between loops?
function getFBLikes($postid) {
//Get total number of likes per post
$query = '/likes?summary=1&filter=stream';
$request_likes = BASE_URL
.$postid
.$query
.ACCESS_TOKEN;
$result_likes = json_decode(file_get_contents($request_likes), true);
foreach ($result_likes as $a => $b) {
if(isset($b['total_count'])) {
$likes = $b['total_count'];
echo $likes /* THIS APPEARS AS A CORRECT VALUE */
}
}
}
function getPostDetails($array){
foreach ($array as $a => $b) {
if(isset($b['type'])) {
if(isset($b['object_id'])){
$postid = $b['object_id'];
$shares = $b['shares']['count'];
$type = $b['type'];
getFBLikes($postid);
echo $likes; /* THIS IS NULL */
}
}
}
}
Add
return $likes;
to getFBLikes and
use it like this in getPostDetails
$likes = getFBLikes($postid);
function getFBLikes($postid) {
//Get total number of likes per post
$query = '/likes?summary=1&filter=stream';
$request_likes = BASE_URL
.$postid
.$query
.ACCESS_TOKEN;
$result_likes = json_decode(file_get_contents($request_likes), true);
foreach ($result_likes as $a => $b) {
if(isset($b['total_count'])){
$likes = $b['total_count'];
//ADDED
return $likes;
}
}
}
function getPostDetails($array){
foreach ($array as $a => $b) {
if(isset($b['type'])) {
if(isset($b['object_id'])){
$postid = $b['object_id'];
$shares = $b['shares']['count'];
$type = $b['type'];
//CHANGED
$likes = getFBLikes($postid);
echo $likes; /* THIS SHOULD NO LONGER BE NULL */
}
}
}
}
Should do the trick.
The problem you have here is getPostDetails is taling to getFBLikes,
but getFBLikes is not 'responsing' (returning) anything to you're getPostDetails so when you tried echoing the number of likes it was going to be null because essentially it wasnt being told how many likes there were
You need to have getFBLikes() return a value.
From the docs:
If called from within a function, the return statement immediately ends execution of the current function, and returns its argument as the value of the function call.
Sample solution:
in getFBLikes() add:
echo $likes /* THIS APPEARS AS A CORRECT VALUE */
return $likes
in getPostDetails() you can access the value with:
$likes = getFBLikes($postid); /* getFBLikes() will be return a value in $likes

Setting a variable to an operator then executing it

I'm new to PHP in general. I was messing with this code until I wanted to execute the function in one set instead of having to set and add, sub, div, mult function. How do I go about setting the variable operator with the two num sets?
Example pseudo code:
<?php
$Num1 = 10;
$Num2 = 5;
$operation = /;
$Sum = $Num1 $operation $Num2;
return $Sum;
Or something like:
<?php
// creating Class "Math"
class math {
//Executing the function
function exec($info = array()) {
return $info['num1'] $info['operation'] $info['num2'];
}
}
// Set info
$info = array(
'num1' => 10,
'num2' => 5,
'operation' => '/'
);
//execute the OOP
$math = new math;
echo $math->exec($info);
What you are asking for is referred to as the Strategy Pattern.
One way to do this is to define your functions
$multiply = function($operand0, $operand1) {
return $operand0*$operand1;
};
$add = function($operand0, $operand1) {
return $operand0+$operand1;
};
Then using your sample code:
class math {
//Executing the function
function exec($info = array()) {
return $info['operation']($info['num1'], $info['num2']);
}
}
// Set info
$info = array(
'num1' => 10,
'num2' => 5,
'operation' => $add
);
//execute the OOP
$math = new math;
echo $math->exec($info); //will print 15

PHP equivalent of Excel vlookup on array

After looking for a built in function in php I couldn't find a similar function to Excel's vlookup function.
I need a function that takes in an array and a lookup value and return the required info. So for example:
<?php
$baseCalculationPrice = [
0 => 50, //for values <=500 but >0
500 => 18, //for values <=3000 but >500
3000 => 15, //for values <=5000 but >3000
5000 => 14, //for values >5000
];
//Examples
$numPages = 499;
echo vlookup($numPages,$baseCalculationPrice); //should output 50
$numPages = 500;
echo vlookup($numPages,$baseCalculationPrice); //should output 50
$numPages = 501;
echo vlookup($numPages,$baseCalculationPrice); //should output 18
$numPages = 3000;
echo vlookup($numPages,$baseCalculationPrice); //should output 18
$numPages = 3001;
echo vlookup($numPages,$baseCalculationPrice); //should output 15
$numPages = 5000;
echo vlookup($numPages,$baseCalculationPrice); //should output 15
$numPages = 5001;
echo vlookup($numPages,$baseCalculationPrice); //should output 14
function vlookup($value,$array){
//magic code
return ....;
}
?>
I'm stuck even with the logic behind such a function, so any help would be great - thanks.
function vlookup($lookupValue,$array){
$result;
//test each set against the $lookupValue variable,
//and set/reset the $result value
foreach($array as $key => $value)
{
if($lookupValue > $key)
{
$result = $value;
}
}
return $result;
}
function testDeductionRate(){echo $this->deductionRate('ks',300);//zone and time are parameter for deductionRate() }
//deduction will be acted as vlookup (rangeLookup true)
function deductionRate($zone,$time){
$actualRate = 0;
$allRate = array(
'tg'=>array(0=>0,20=>200,30=>300,40=>400,50=>500),
'ks'=>array(0=>0,20=>100,30=>200,40=>300,50=>400),
'pc'=>array(0=>0,20=>50,30=>100,40=>200,50=>300)
);
if(isset($allRate[$zone])){
$rate = $allRate[$zone];
foreach($rate as $key=>$val){
if($time>=$key) $actualRate = $val;
}
}else{
return -1; //-1 means error
}
return $actualRate;
}
Try this if you would like to query on multi dimension associative array:
function vlookup($lookup_vakue, $lookup_array, $lookup_column, $result_column)
{
foreach ($lookup_array as $item) {
if ($item[$lookup_column] == $lookup_vakue) {
return $item[$result_column];
}
}
return false;
}
Sample Data
$data =
[
['id'=>1,'price'=>100],
['id'=>2,'price'=>200],
['id'=>3,'price'=>300]
];
Query Option
$result = vlookup('2',$data, 'id','price');
Result:
200
$getbase= function($amount) use ($baseCalculationPrice)
{
return (end(array_filter(
$baseCalculationPrice,function ($key) use ($amount)
{
return $key < $amount;
},
ARRAY_FILTER_USE_KEY
)));
};
amount 150 result 50
amount 1500 result 18
amount 25000 result 14

Calling a function from highcharts upon clicking the piechart

I would like to call a function when someone clicks on the pie-chart which I built using Highchart.
My pie chart code is:
function open_risk_level_pie()
{
$chart = new Highchart();
$chart->chart->renderTo = "open_risk_level_pie";
$chart->chart->plotBackgroundColor = lightblue;
$chart->chart->plotBorderWidth = null;
$chart->chart->plotShadow = false;
$chart->title->text = "Risk Level";
$chart->tooltip->formatter = new HighchartJsExpr("function() {
return '<b>'+ this.point.name +'</b>: '+ this.point.y; }");
$chart->plotOptions->pie->allowPointSelect = 1;
$chart->plotOptions->pie->cursor = "pointer";
$chart->plotOptions->pie->dataLabels->enabled = false;
$chart->plotOptions->pie->showInLegend = 1;
$chart->plotOptions->pie->colors = array('red', 'orange', 'yellow', 'black');
$chart->credits->enabled = false;
$array = //some db access code
$high = $array[0][0];
$medium = $array[1][0];
$low = $array[2][0];
// If the array is empty
if (empty($array))
{
$data[] = array("No Data Available", 0);
}
// Otherwise
else
{
// Create the data array
foreach ($array as $row)
{
$data[] = array($row['level'], (int)$row['num']);
}
$chart->series[] = array('type' => "pie",
'name' => "Level",
'data' => $data);
}
echo "<div id=\"open_risk_level_pie\"></div>\n";
echo "<script type=\"text/javascript\">";
echo $chart->render("open_risk_level_pie");
echo "</script>\n";
}
Now I want to call a function whenever someone clicks on the pie chart. I have searched a lot, but unable to find. Some sites mentioned to use "formatter", but I failed to use it. If formatter is the solution for my question please give me steps for the above code.
Use an on click event for a slice.
Docs.

Looping class, for template engine kind of thing

I am updating my class Nesty so it's infinite but I'm having a little trouble.... Here is the class:
<?php
Class Nesty
{
// Class Variables
private $text;
private $data = array();
private $loops = 0;
private $maxLoops = 0;
public function __construct($text,$data = array(),$maxLoops = 5)
{
// Set the class vars
$this->text = $text;
$this->data = $data;
$this->maxLoops = $maxLoops;
}
// Loop function
private function loopThrough($data)
{
if( ($this->loops +1) > $this->maxLoops )
{
die("ERROR: Too many loops!");
}
else
{
$keys = array_keys($data);
for($x = 0; $x < count($keys); $x++)
{
if(is_array($data[$keys[$x]]))
{
$this->loopThrough($data[$keys[$x]]);
}
else
{
return $data[$keys[$x]];
}
}
}
}
// Templater method
public function template()
{
echo $this->loopThrough($this->data);
}
}
?>
Here is the code you would use to create an instance of the class:
<?php
// The nested array
$data = array(
"person" => array(
"name" => "Tom Arnfeld",
"age" => 15
),
"product" => array (
"name" => "Cakes",
"price" => array (
"single" => 59,
"double" => 99
)
),
"other" => "string"
);
// Retreive the template text
$file = "TestData.tpl";
$fp = fopen($file,"r");
$text = fread($fp,filesize($file));
// Create the Nesty object
require_once('Nesty.php');
$nesty = new Nesty($text,$data);
// Save the newly templated text to a variable $message
$message = $nesty->template();
// Print out $message on the page
echo("<pre>".$message."</pre>");
?>
Here is a sample template file:
Dear <!--[person][name]-->,
Thanks for contacting us regarding our <!--[product][name]-->. We will try and get back to you within the next 24 hours.
Please could you reply to this email to certify you will be charged $<!--[product][price][single]--> for the product.
Thanks,
Company.
The problem is that I only seem to get "string" out on the page... :(
Any ideas?
if(is_array($data[$keys[$x]]))
{
$this->loopThrough($data[$keys[$x]]);
}
else
{
return $data[$keys[$x]];
}
You need to return from the first if statement.
if(is_array($data[$keys[$x]]))
{
return $this->loopThrough($data[$keys[$x]]);
}
else
{
return $data[$keys[$x]];
}
This will get you a result back when you recurse. You're only getting "string" back right now because that key is only 1 level deep in your array structure.

Categories