why does getting array length give undefined? - php

i have this code:
$.getJSON('newMessageDetails', function (json)
{
var old_id = document.getElementById("td_id").value;
var messages_count = Object.keys(json).length;
console.log(messages_count);
console.log(json);
last_id = json[messages_count]["msgId"];
});
the json[messages_count]["msgId"] gives undefined in the console??
my newMessageDetails:
public function executeNewMessageDetails(sfWebRequest $request)
{
$profile_id = $this->getUser()->getAttribute('profile_id','zero');
$new_msgs = RcMessageBoxTablePeer::getNewMessages($profile_id);
$hr=2;
$i=1;
if (count($new_msgs) >= 1)
{
foreach ($new_msgs as $row)
{
$date = $row->getCreatedAt();
//$cd = strtotime($date);
//$newdate = date('Y-m-d H:i:s', mktime(date('h',$cd), date('i',$cd), date('s',$cd), date('m',$cd), date('d',$cd), date('Y',$cd)));
$subject = $row->getSubject();
$message = $row->getMessage();
$from = $row->getProfileIdFrom();
$id = $row->getId();
$uc_record = RcProfileTablePeer::getById($from);
$uc_from = $uc_record->getUniqueCode();
$output[$i] = array("td_date" => $date, "td_subject" => $subject, "td_from" => $uc_from, "td_message" => $message, "msgId" => $id , "i" => $i);
$i++;
}
return $this->renderText(json_encode($output));
}
}
console.log(json) gives:
5
list:98
Object
543: Object
544: Object
545: Object
546: Object
547: Object
i: 1
msgId: 547
td_date: "2011-11-29 11:33:05"
td_from: "CHARLIE000RC"
td_message: "tooltip show message test 2 id 547"
td_subject: "Freechat message"
can some-one explain please? dont know what im doing wrong though
thanks

Objects don't have a length property. try this.
var obj = jQuery.parseJSON(json);
obj.length();
or you can try this.
Object.keys(json).length;

If you would like a count of all keys you could rewrite it to this:
$.getJSON('newMessageDetails', function (json)
{
...;
var messages_count = Object.keys(json).length;
console.log(messages_count);
});

you should just iterate through the object and count . Thats the only way you can really know how many 'meaningful' objects you have in your object.

Related

Is there a way to return one or many items without repeating yourself?

I seem to be stuck. I have a funtion that calculates the salary. I am trying to make it so that I can specify one or many users when I call the function. But I ran into 2 problems. One is how could I construct the output result if I specify multiple user ids. And second problem is how not to repeat my code twice (for one and many users). It works fine if I only need to get it for one user.
I would like to be able to call it like this:
// Get salary for user id: 10
$salary = Salary::getSalary([10], '2018-12-01', '2018-12-31');
echo $salary->user->fullname;
echo $salary->salary->total;
echo $salary->checked;
// Get salary for users - 10, 20, 30
$salaries = Salary::getSalary([10, 20, 30, '2018-12-01', '2018-12-31');
foreach ($salaries as $salary) {
echo $salary->user->fullname;
echo $salary->salary->total;
echo $salary->checked;
}
Here is my function
public function getSalary($user_id, $date_from, $date_to)
{
$salary = new stdClass;
if ( count($user_id) == 1 ) {
$salary->user = new stdClass;
$salary->user->fullname = self::getUserById($user_id)->fullname;
$salary->user->phone = self::getPhone($user_id);
$salary->user->email = self::getUserById($user_id)->e_mail;
$salary->salary = self::getSalary($user_id, $date_from, $date_to);
$salary->checked = self::isChecked($user_id, $date_from, $date_to);
} else if ( count($user_id) > 1 ) {
foreach ($user_id as $employee)
{
$salary->employee = new stdClass;
$salary->employee->fullname = self::getUserById($user_id)->fullname;
$salary->employee->phone = self::getPhone($user_id);
$salary->employee->email = self::getUserById($user_id)->e_mail;
$salary->employee->siawork = self::getUserById($user_id)->siawork;
$salary->salary = self::getSalary($user_id, $date_from, $date_to);
$salary->checked = self::isChecked($user_id, $date_from, $date_to);
}
}
return $salary;
}
I think if when you call the function and there is only 1 entry, then you can convert this to an array so that you always use the same code to process the data, and build an array of the salary data to send back...
public function getSalary($user_id, $date_from, $date_to)
{
$salaries = [];
if ( !is_array($user_id) ) {
$user_id = [$user_id];
}
foreach ($user_id as $employee)
{
$salary->employee = new stdClass;
$salary->employee->fullname = self::getUserById($user_id)->fullname;
$salary->employee->phone = self::getPhone($user_id);
$salary->employee->email = self::getUserById($user_id)->e_mail;
$salary->employee->siawork = self::getUserById($user_id)->siawork;
$salary->salary = self::getSalary($user_id, $date_from, $date_to);
$salary->checked = self::isChecked($user_id, $date_from, $date_to);
$salaries[] = $salary;
}
return $salaries;
}
You could if you wish, return a single entry if you want to by amending the last part of the code...
if ( count($user_id) == 1 ) {
$salaries = $salaries[0];
}
return $salaries;
}
Here's my solution for your class function. It looks like you were trying to return a single object and overwriting employee every time. If you can accept an array of ID's, it makes sense to return an array of salaries. Does this make sense?
public function getSalary($user_id, $date_from, $date_to)
{
//Return an array of salary objects to match your array of id inputs
$salary = [];
if ( ! is_array($user_id) ) {
//In case a non-array is entered
$user_id = [$user_id];
}
// A foreach will work even if there's only one user ID given,
// as long as it's an array (which it should be by this point)
foreach ($user_id as $id)
{
//Get your salary object by id
$this_user = new stdClass;
$this_user->user = new stdClass;
$this_user->user->fullname = self::getUserById($id)->fullname;
$this_user->user->phone = self::getPhone($id);
$this_user->user->email = self::getUserById($id)->e_mail;
$this_user->salary = self::getSalary($id, $date_from, $date_to);
$this_user->checked = self::isChecked($id, $date_from, $date_to);
//Put it in the output array
$salary[] = $this_user;
}
return $salary;
}
Note, please validate all these inputs! Make sure that putting in something unexpected to $user_id or $date_from or $date_to will not break everything without at least showing an error.

convert doctrine resultset to json from findby query using zend json

I've seend much assistance for everything BUT transforming data when using the findBy query.
What I want is a json string of the resulset from this query ensuring that the objects are serialized so i can use this somewhere else:
$posts = $entityManager->getRepository(\Application\Entity\Post::class)
->findBy(['status'=>\Application\Entity\Post::STATUS_PUBLISHED],
['dateCreated'=>'DESC']);
Json::encode($posts,true) from Zend Framework Json but the data is not showing up when i do this.
The result will be a json encoded string with the entity objects that i can pass somewhere else
I will use for the decoding:
\Zend\Json\Decoder::decode($posts,\Zend\Json\Json::TYPE_OBJECT)
UNLESS I should be using \Zend\Json\Json::TYPE_ARRAY)
Here is the way I do it :
include : use Zend\Json\Json;
here is my example of function / action :
public function getListAction(){
$request = $this->getRequest();
if($request->isPost()){
// recuperer le produit choisi :
$element = $request->getPost("element");
$result = null;
$result = $this->getEntityManager()->getRepository('Application\Entity\Element')->findBy(array('etat' => 'valide' , 'pkElement' => $element));
$champs = array();
$i = 0;
foreach ($result as $value) {
$champs[$i] = array("id"=>$value->getPkElement() , "nom"=>$value->getNom());
$i++;
}
$data = array(
'result' => true,
'data' => $champs
);
return $this->getResponse()->setContent(Json::encode($data));
}
}
Then the call in the view.phtml :
$.post('/application/controller_name/getList', {element: $("select[name=element]").val()}, function(result) {
var options = $("select[name=element]");
var obj = JSON.parse(result);
var data = obj.data;
var selected = "";
options.empty();
for (var i = 0; i < data.length; i++) {
options.append($("<option />").val(data[i]['id']).text(data[i]['nom']));
}
});
Hope it helps.

JSON Parsing - How to get rid of leading tab character in front of data?

I am trying to remove a tab character from a json_encoded data from php? Every time I try to fetch data from the script as JSON enocded format I use the following code below to parse my data but can not get the jsonStr to be parsed.
The error I am getting is
Error: JSON.parse: unexpected character at line 1 column 1 of the JSON
data
Code
jsonStr = data.toString();
jsonStr = JSON.stringify(jsonStr.replace("\t",""));
totJSON = JSON.parse(jsonStr['totalActionItems']);
How do I resolve this error to parse a well formed json string correctly?
EDIT
Corrected Parsing Code (JS)
$.ajax({url: "/dashboard/chartdata.php?chart=buildup", success: function(data)
{
jsonStr = data.replace(/\t/g, "");
console.log(jsonStr);
json = JSON.parse(jsonStr);
totJSON = json['totalActionItems'];
PHP Code
function getData($field, $rows)
{
$minDate = $rows[0][$field];
$maxDate = $rows[count($rows)-1][$field];
$date = $minDate;
$findDate = $minDate;
$idx = 0;
$tot = 0;
$dates = array();
$numActionItems = array();
while ($date < $maxDate)
{
if ($rows[$idx][$field] == $date)
{
$tot += $rows[$idx]['numactionitems'];
$idx++;
}
$timestamp = strtotime($date);
$date = date('Y-m-d', strtotime($date . "+1 days"));
$numActionItems[] = array('x'=>$timestamp*1000, 'y'=>$tot);
}
return $numActionItems;
}
function getBuildUpData($field)
{
$manageCharts = new manageCharts();
$rows = $manageCharts->buildup($field);
$items = getData($field, $rows);
return $items;
}
if (isset($_GET['chart']) && $_GET['chart'] == 'buildup')
{
$json = json_encode(['totalActionItems' => getBuildUpData('assigneddate'),
'ecdItems' => getBuildUpData('ecd'),
'originalDueItems' => getbuildUpData('duedate'),
'closedItems' => getBuildUpData('closeddate')]);
echo $json;
}
The following code helped produce the correct json for processing.
jsonStr = data.replace(/\t/g, "");
//console.log(jsonStr);
json = JSON.parse(jsonStr);
totJSON = json['totalActionItems'];

how to remove the array to string conversion error in 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
?>

PDO - Call to a member function fetch() on a non-object?

I looked at all the other posts on this and none of them came up with exactly what my problem is so here we go:
$dbh stores my PDO connection, if I do a var dump on it, it returns:
object(PDO)#1 (0) { }
So I know my PDO connection is working. I then use $sth to hold my query:
$c = 2;
$sth = $dbh->query("SELECT * FROM table WHERE ID = " . $c);
Then to make sure this is working I did:
echo $sth->rowCount();
That return a value of 6. So I know it is grabbing some rows. My next step of checking my problem was to fetch a single row like the following:
$row = $sth->fetch()
print_r($row);
This returned a single row (as it should) with the $row array filled exactly how I would expect it (column names as keys and column values as the array value).
So we are good up to this point. Once I move $row = $sth->fetch() into a while loop my script fails the error it returns is: Call to a member function fetch() on a non-object
Here is my while loop:
while($row = $sth->fetch()){
//while loop stuff here
}
I know it has something to do with the condition of the loop because even when I comment out all the stuff in the middle it still isn't working. What am I doing wrong? Why won't this work? I'm beyond confused on this as it has worked in the past with all the PDO I have done but for some reason it is failing in this script.
If anyone has any tips or something that can help it would be greatly appreciated.
EDIT Since ninetwozero's post worked, I'm posting my class and basically everything I've got to get this figured out.
class html_elements {
var $units;
var $useMaps;
var $cid;
var $uid;
var $companyMoney;
var $currCity;
var $terminals;
var $termLocs;
var $cityArray;
var $cargoArray;
var $cargo;
var $tid;
var $truckArray;
var $load;
var $cityID;
var $cargoID;
var $xp;
var $gasPrice;
var $warning;
function __construct($u, $maps, $c, $userID, $cMoney, $dbh, $city, $tid, $xp){
$this->units = $u;
$this->useMaps = $maps;
$this->cid = $c;
$this->uid = $userID;
$this->companyMoney = $cMoney;
$this->currCity = $city;
$this->terminals = array();
$this->termLocs = array();
$this->cityArray = array();
$this->cargoArray = array();
$this->cargo = array();
$this->tid = $tid;
$this->truckArray = array();
$this->load = 0;
$this->cityID = array();
$this->cargoID = array();
$this->xp = $xp;
$this->gasPrice = 0;
$sth = null;
$sth = $dbh->query("SELECT * FROM tblCTerminals WHERE companyID = " . $c);
//THIS LOOP FAILS
while($row = $sth->fetch()){
$this->termLocs[] = $row['Location'];
}
}
Then in another file that has my class file included in it is:
$h = new html_element($u->get_units(), $u->get_maps(), $u->get_company(), $u->get_user_id(), $c->get_money(), $dbh, $u->get_city(), $u->get_truck_id(), $u->get_xp());
Each of those getters work, I tested them. Also $dbh is what is used my connection file that is included before anything else. So I know all of that is working.
I got to say that you've encountered a pretty interesting error, so let's try some things to pinpoint the cause:
if( $sth == null ) die('My sth is null at #1');
while( $row = $sth->fetch() ) {
if( $row == null ) die('My row is null at #2');
echo '<pre>';
print_r($row);
echo '</pre>';
}
Let me know what this tells you.
Edit:
$sql = 'SELECT * FROM tblCTerminals WHERE companyID = ' . $c;
if( intval($c) == 0 ) { die('Aaaaaaaaaa.......aaaaah.');
foreach ($dbh->query($sql) as $row) {
echo '$row[\'Location\'] is: ' . $row['Location'] .'<br />';
$this->termLocs[] = $row['Location'];
}

Categories