Here is my problem :
I have a PHP file, that should return multiple records,
everything worked fine... but, i don't know why, probably because of a little mistake somewhere... now it doesn't work anymore...
my Json_encode(my php) returns this :
{"1":{"id":"2222","name":"ERESRS"},"2":{"id":"1111","name":"LJLJM"}}
instead of simply :
[{"id":"2222","name":"ERESRS"},{"id":"1111","name":"LJLJM"}]
anybody had this issue before?
i already checked again and again my php file, and i don't find where this "false array" comes from...
thanks for help
Here is the js code :
$.ajax({
type : 'POST',
url : './php/getBenefListe.php',
data : {'id':idSoc},
error : function(){
alert('ERREUR MISE A JOUR DE LA LISTE');
},
success : function(response){
$("#benefListe").empty();
$('#benefListe').append($('<option>',{
value : '',
text : 'Choisissez dans la liste'
}));
alert("REPONSE : "+response);
var myData = JSON.parse(response);
for(var i=0;i<myData.length;i++){
var id = myData[i].id;
if(id-latestBenef > 0){
latestBenef = id;
}
var nom = myData[i].nom;
var prenom = myData[i].prenom;
var rue = myData[i].rue;
var numero = myData[i].num;
var boite = myData[i].bte;
var cp = myData[i].cp;
var loc = myData[i].loc;
if(rue!="" && numero!=""){
rue = rue+", "+numero;
}
if(cp!="" && loc!=""){
loc = "- "+cp+" "+loc;
}
var field = nom+" "+prenom+" ; "+rue+" "+boite+" "+loc;
$('#benefListe').append($('<option>',{
value : id,
text : field
}));
}
alert("B\351n\351ficiaire Ajout\351!");
$("#benefListe option[value="+latestBenef+"]").prop('selected',true);
$("#benefListe").change();
}
});
here is the php file called :
include "./functions.php";
if(isset($_POST['id']) && ($_POST['id']!='')){
$id = $_POST['id'];
$db = connectToDb('test');
$myArray = array();
$i = 0;
$getBenefIds = "SELECT DISTINCT IDPERSONNE FROM socrsp WHERE (IDSOCIETE = $id);";
$benefIds = $db->prepare($getBenefIds);
$benefIds->execute();
$count = $benefIds->rowCount();
if($count>0){
foreach($benefIds as $benefId){
$getBenef = "SELECT IDPERSONNE,NOM,PRENOM,ADRESSE,NUMERO,BTE,IDCOPOSTAL,CODEPAYS FROM personne WHERE IDPERSONNE = ".$benefId['IDPERSONNE'];
$myBenef = $db->prepare($getBenef);
$myBenef->execute();
foreach($myBenef as $benef){
if(!(is_numeric($benef['ADRESSE']))){
$myArray[$i]['id'] = $benef['IDPERSONNE'];
$myArray[$i]['nom'] = $benef['NOM'];
$myArray[$i]['prenom'] = $benef['PRENOM'];
$myArray[$i]['rue'] = '';
$myArray[$i]['num'] = '';
$myArray[$i]['rue'] = $benef['ADRESSE'];
$myArray[$i]['num'] = $benef['NUMERO'];
$myArray[$i]['bte'] = $benef['BTE'];
//RECUP CP ET LOCALITE
if((isset($benef['IDCOPOSTAL']) && ($benef['IDCOPOSTAL']!='0') && ($benef['IDCOPOSTAL']!='2913'))&&($benef['CODEPAYS']=="B")){
$whereQuery = "SELECT CODEPOSTAL,LIBLOCALITE FROM copostal WHERE IDCOPOSTAL = ".$benef['IDCOPOSTAL'];
$where = $db->prepare($whereQuery);
$where->execute();
foreach($where as $w){
$myArray[$i]['cp'] = $w['CODEPOSTAL'];
$myArray[$i]['loc'] = $w['LIBLOCALITE'];
}
}else if((isset($benef['IDCOPOSTAL']) && ($benef['IDCOPOSTAL']!='0'))&&($benef['CODEPAYS']!="B")){
$whereQuery = "SELECT CPEXTERNE,LOCEXTERNE FROM cpostext WHERE IDCPOSTEXT = ".$benef['IDCOPOSTAL'];
$where = $db->prepare($whereQuery);
$where->execute();
foreach($where as $w){
$myArray[$i]['cp'] = $w['CPEXTERNE'];
$myArray[$i]['loc'] = $w['LOCEXTERNE'];
}
}else{
$myArray[$i]['cp'] = '';
$myArray[$i]['loc'] = '';
}
$i++;
}else{
$i++;
}
}
}
}
echo json_encode($myArray);
$db = null;
}
It looks like you're setting manually the keys for the PHP array or editing it in some way. Compare the following results:
<?php
$a = ['hello', 'world'];
echo json_encode($a);
// ["hello","world"]
$b = [1 => 'hello', 2 => 'world'];
echo json_encode($b);
// {"1":"hello","2":"world"}
$b = ['hello', 'world', 'how', 'are', 'you'];
unset($b[2]);
echo json_encode($b);
// {"0":"hello","1":"world","3":"are","4":"you"}
As #amphetamachine suggest, a possible solution is this:
$b = [1 => 'hello', 2 => 'world'];
$b = array_values($b);
echo json_encode($b);
// ["hello","world"]
Another interesting test (your case):
<?php
$a = $b = [];
for ($i = 0; $i < 3; $i++) {
$a[$i] = "test";
if ($i != 1) {
$b[$i] = "test";
}
}
echo json_encode($a);
// ["test","test","test"]
echo json_encode($b);
// {"0":"test","2":"test"}
echo json_encode(array_values($b));
// ["test","test"]
From which, we can get that you do need that array_values() if you want to set not-consecutive array keys.
Related
What I want to do is When I enter all my information (for client ID 199 in the picture) In my account being submit it, it goes into the database. BUT I want it to change to something and so i added an if statement
Here the code im adding to the existing code already at the BOTTOM of the code
if ($vpr_clid == 199) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
if the ($vpr_clid = 199)
i want the clname to be "Shelley Madsen And Associates" then what is show in the table below instead of "Nice and White Smiles" (that an example of the results look like)
but when i chcek the database it not changing it and still show "Nice and White Smiles :(
I dont see any error, so it might be the placement of the code i have to put the IF statement in the huge php file? Dont know how to fix this issue
Thanks (the code below is the base code before i added the If statement)
I also insert the if statement before the function were called but still didnt work example
if ($vpr_clid == 199) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
$result = InsertIntoPayReminder($link, $vars);
$result = GetVpr_Id($link, $vars);
<?php
session_start();
if ($_SESSION['company'] != "ACB") {
// redirect to the logout page
$redirect = 'logout.php';
include './includes/redirect.php';
}
class variables_obj {
var $vpr_plan = '';
var $vpr_id = '';
var $vpr_clid = '';
var $vpr_cl_name = '';
var $vpr_cl_phone = '';
var $vpr_call_start_date = '';
var $vpr_db_account = '';
var $vpr_db_fname = '';
var $vpr_db_mname = '';
var $vpr_db_lname = '';
var $vpr_rp_fname = '';
var $vpr_rp_mname = '';
var $vpr_rp_lname = '';
var $vpr_rp_address = '';
var $vpr_rp_city = '';
var $vpr_rp_state = '';
var $vpr_rp_zipcode = '';
var $vpr_rp_phonenum = '';
var $vpr_rp_phonetype = '';
var $vpr_date_entered = '';
var $newrecdt = '';
var $vpl_day_offset = '';
var $vpl_action = '';
var $vpr_promocode = '';
}
function ScrubPhone($old_phone_num) {
$phone_length = strlen($old_phone_num);
$new_phone_num = "";
for($i = 0; $i < $phone_length; $i = $i + 1) {
if(is_numeric($old_phone_num[$i])) {
$new_phone_num .= $old_phone_num[$i];
}
}
return $new_phone_num;
}
function ScheduleCreated($link, $vars) {
$query = "UPDATE v_payreminder SET vpr_schedule_created = '1' WHERE vpr_id='".$vars->vpr_id."'";
if (!mysql_query($query,$link)) {
die('Error: ' . mysql_error());
}
return true;
}
function CreateScheduleRow($link, $vars){
// echo "vpl_day_offset: ".$vars->vpl_day_offset."<br>";
// echo "vpl_action: ".$vars->vpl_action."<br>";
$plus_days = " +".$vars->vpl_day_offset." days";
// echo "plus days: ".$plus_days."<br>";
$date_offset = strtotime(date("Y-m-d", strtotime($vars->vpr_date_entered)).$plus_days);
$date_offset = date("Y-m-d", $date_offset);
// echo "date_offset: ".$date_offset."<br>";
// $date_offset = strtotime(date("Y-m-d",strtotime($vars->vpr_date_entered))." +".$vars->vpl_day_offset." days");
// $date_offset = strtotime(date("Y-m-d", strtotime($date)) . " +1 day");
// echo "date_offset: ".$date_offset."<br>";
$query = "INSERT INTO v_pr_schedule (
vpr_id,
vsc_plan,
vsc_date_entered,
vsc_action,
vsc_action_date,
vsc_status
) VALUES (
'$vars->vpr_id',
'$vars->vpr_plan',
'$vars->vpr_date_entered',
'$vars->vpl_action',
'$date_offset',
'VACT')";
//echo "query: ".$query."<br>";
if (!mysql_query($query,$link)) {
die('Error: ' . mysql_error());
}
return true;
}
function CreateSchedule($link, &$vars) {
// CREATE SCHEDULE
$query = " SELECT vpl_day_offset, vpl_action, vpl_condition
FROM v_plan
WHERE vpl_plan = '".$vars->vpr_plan."'";
// echo "query: ".$query."<br>";
$qresult = mysql_query($query);
if (!$qresult) {
print(mysql_error());
}
if ($qresult && mysql_num_rows($qresult) > 0 ) {
while ($row = mysql_fetch_array($qresult, MYSQL_ASSOC)) {
$vars->vpl_day_offset = $row['vpl_day_offset'];
$vars->vpl_action = $row['vpl_action'];
if ($row['vpl_condition'] == 'OO') {
CreateScheduleRow($link, $vars);
}
}
}
return true;
}
function InsertIntoPayReminder($link, &$vars) {
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
//echo "Client Name: ".$vars->vpr_cl_name."<br><br>";
//exit();
$sql="INSERT INTO v_payreminder (
vpr_clid,
vpr_cl_name,
vpr_cl_phone,
vpr_call_start_date,
vpr_db_account,
vpr_db_fname,
vpr_db_mname,
vpr_db_lname,
vpr_rp_fname,
vpr_rp_mname,
vpr_rp_lname,
vpr_rp_phonenum,
vpr_rp_phonetype,
vpr_rp_address,
vpr_rp_city,
vpr_rp_state,
vpr_rp_zipcode,
vpr_promo,
vpr_date_entered) VALUES (
'$vars->vpr_clid',
'$vars->vpr_cl_name',
'$vars->vpr_cl_phone',
'$vars->vpr_call_start_date',
'$vars->vpr_db_account',
'$vars->vpr_db_fname',
'$vars->vpr_db_mname',
'$vars->vpr_db_lname',
'$vars->vpr_rp_fname',
'$vars->vpr_rp_mname',
'$vars->vpr_rp_lname',
'$vars->vpr_rp_phonenum',
'$vars->vpr_rp_phonetype',
'$vars->vpr_rp_address',
'$vars->vpr_rp_city',
'$vars->vpr_rp_state',
'$vars->vpr_rp_zipcode',
'$vars->vpr_promocode',
'$vars->vpr_date_entered')";
if (!mysql_query($sql,$link)) {
die('Error2: ' . mysql_error());
}
return true;
}
function GetVpr_Id($link, &$vars) {
// Find out what vpr_id is
$query = "SELECT vpr_id FROM v_payreminder ";
$query .= "WHERE vpr_clid = '".$vars->vpr_clid."' AND vpr_date_entered = '".$vars->vpr_date_entered."'";
$qresult = mysql_query($query);
if (!$qresult) {
print(mysql_error());
}
if ($qresult && mysql_num_rows($qresult) > 0 ) {
$row = mysql_fetch_array($qresult, MYSQL_ASSOC);
$vars->vpr_id = $row['vpr_id'];
}
}
function InsertInActivity($link, $vars) {
// ENTER INTO ACTIVITY
$vaction_desc = 'PATIENT ENTERED';
$sql = "INSERT INTO v_pr_activity (
vpr_id,
va_plan,
va_action_dttm,
va_action_code,
va_action_desc,
va_disposition_code,
va_disposition_desc,
va_status_code,
va_status_desc
) VALUES (
'$vars->vpr_id',
'$vars->vpr_plan',
'$vars->vpr_date_entered',
'VINIT',
'$vaction_desc',
'SUCCESS',
'SUCCESS',
'VACT',
'ACTIVE'
)";
if (!mysql_query($sql,$link)) {
die('Error: ' . mysql_error());
}
}
include './includes/dblogin.php';
$vars = new variables_obj();
$vars->vpr_plan = 'VP01';
$vars->vpr_clid = $_SESSION['userid'];
//-------------------------------------------------------
// No commas can be in client name or they will
// mess up the Global Connect CSV file.
//-------------------------------------------------------
$vpr_cl_name = $_SESSION['username'];
$vpr_cl_name = str_replace(",", " ", $vpr_cl_name);
$vars->vpr_cl_name = $vpr_cl_name;
//-------------------------------------------------------
//-------------------------------------------------------
$vars->vpr_cl_phone = ScrubPhone($_SESSION['uphone']);
$vars->vpr_call_start_date = '0000-00-00';
$vars->vpr_db_account = $_POST['ndaccnum'];
$vars->vpr_db_fname = $_POST['ndfreqname'];
$vars->vpr_db_mname = $_POST['ndmname'];
$vars->vpr_db_lname = $_POST['ndlreqname'];
$vars->vpr_rp_fname = $_POST['ndrfreqname'];
$vars->vpr_rp_mname = $_POST['ndrmname'];
$vars->vpr_rp_lname = $_POST['ndrlreqname'];
$vars->vpr_rp_address = '';
$vars->vpr_rp_city = '';
$vars->vpr_rp_state = $_POST['ndrstatereqname'];
$vars->vpr_rp_zipcode = $_POST['ndrreqzipcode'];
$phonenumber = $_POST['1ndrreqphone'].$_POST['2ndrreqphone'].$_POST['3ndrreqphone'];
$vars->vpr_rp_phonenum = $phonenumber;
$vars->vpr_rp_phonetype = $_POST['treqphone'];
$vars->vpr_date_entered = date('Y-m-d H:i:s');
$vars->newrecdt = date('Ymd');
$vars->vpr_promocode = $_POST['promocode'];
// echo "vpr_plan: ".$vars->vpr_plan."<br>";
// echo "vpr_date_entered: ".$vars->vpr_date_entered."<br>";
// echo "newrecdt: ".$vars->newrecdt."<br>";
// echo "vpr_clid: ".$vars->vpr_clid."<br>";
// echo "vpr_id: ".$vars->vpr_id."<br>";
$result = InsertIntoPayReminder($link, $vars);
$result = GetVpr_Id($link, $vars);
$result = InsertInActivity($link, $vars);
$result = CreateSchedule($link, $vars);
$result = ScheduleCreated($link, $vars);
// echo "vpr_id: ".$vars->vpr_id."<br>";
mysql_close($link);
// redirect
$redirect = 'vpayremind.php';
include './includes/redirect.php';
?>
okay referencing the following lines..
if ( $vpr_clid == 199 ) {
$vpr_cl_name = "Shelley Madsen And Associates";
}
$result = InsertIntoPayReminder($link, $vars);
...and then:
function InsertIntoPayReminder($link, &$vars) {
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
so on and so forth... }
it doesnt seem as if you are actually setting the value of the class object. You seem to be setting some arbitrary php variable to the name you want, and then passing a totally different ' $vars ' object into the function. I don't see any reason to believe that the ' $vars ' you are passing into the function call contains the name value you want it to contain. You should be assigning the value of ' $vars ' before passing it in.
For instance:
if ( $vpr_clid == 199 ) {
$vars[ 'vpr_cl_name' ] = "Shelley Madsen And Associates";
}
then you can get rid of this line all together:
$vars->vpr_cl_name = strtr($vars->vpr_cl_name, "'", " ");
I am trying to display all records using jason in php.
but display all filed with null value.
I'm using postman for testing purpose.
I don't know what is the problem with that code. I getting null value only.
here is my code :
<?php
header('Content-Type: application/json');
$checkFields = "";
$REQUEST = $_SERVER['REQUEST_METHOD'];
if ($REQUEST == "POST")
{
include "DB/db.php";
$userlist = mysql_query("SELECT * FROM reg_services");
if(mysql_num_rows($userlist) > 0)
{
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
$json = array("success" => 1, "All_User_List" => $ph);
$jsonarray = json_encode($json);
}
}
else
{
$json = array("success" => 0, "message" => "Invalid Request Type(Use POST Method)");
$jsonarray = json_encode($json);
}
echo $jsonarray;
?>
please help me if you are know what is the error in code.
just replace this code with old one
$p = 0;
$ph = array();
while($userlistdata = mysql_fetch_array($userlist))
{
$ph[$p] = array();
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
You need to tell PHP about arrays
while($userlistdata = mysql_fetch_row($userlist))
{
$ph[$p] = array(); // let PHP know it is an array
$ph[$p]["UserId"] = $userlistdata['id'];
$ph[$p]["FirstName"] = $userlistdata['fname'];
$ph[$p]["LastName"] = $userlistdata['lname'];
$ph[$p]["Email"] = $userlistdata['email'];
$ph[$p]["Mobile"] = $userlistdata['mobile'];
$ph[$p]["Password"] = $userlistdata['password'];
$p++;
}
just replace this while loop condition with olde one.
while($userlistdata = mysql_fetch_array($userlist))
now it's work
I'm using Fine Diff from https://github.com/gorhill/PHP-FineDiff in CI. When I use it without JQuery (and AJAX), the results are fine. (I really didn't edit anything)
But when I load it into a div using JQuery, it gives different results
Here's the block of code I'm using in JQuery:
var id = $(document).find('title').text();
var dataString = 'record_type='+recordtype+'&content='+content+'&id='+id+'&series_number='+number;
var prev = $.ajax({
url: getBaseUrl()+'/index.php/edititems/doc/'+id,
type: 'post',
data: dataString,
async: false
}).responseText;
$('.placeholder').html(prev);
And here's the CI code (the same controller and function being used):
$data['doc'] = $this->LoadDb->preview($this->uri->segment(3));
$this->load->library('ciqrcode');
$params['data'] = base_url().'assets/pdfs/'.$data['doc']['record_id'].'.pdf';
$params['level'] = 'H';
$params['size'] = 10;
$params['savename'] = FCPATH.'tes.png';
$this->ciqrcode->generate($params);
$data['doc']['qr'] = '<img src="tes.png" style="height:90px;"/>';
$from_text = $data['doc']['content'];
require_once(APPPATH.'libraries/finediff.php');
$cache_lo_water_mark = 900;
$cache_hi_water_mark = 1100;
$compressed_serialized_filename_extension = '.store.gz';
$granularity = 0;
// $from_text = '';
$to_text = '';
$diff_opcodes = '';
$diff_opcodes_len = 0;
$data_key = '';
$start_time = gettimeofday(true);
$granularity = max(min(intval(2),3),0);
if ( !empty($this->input->post('content')) ) {
$to_text = $this->input->post('content');
}
// limit input
$from_text = substr($from_text, 0, 1024*100);
$to_text = substr($to_text, 0, 1024*100);
// ensure input is suitable for diff
$from_text = mb_convert_encoding($from_text, 'HTML-ENTITIES', 'UTF-8');
$to_text = mb_convert_encoding($to_text, 'HTML-ENTITIES', 'UTF-8');
$granularityStacks = array(
FineDiff::$paragraphGranularity,
FineDiff::$sentenceGranularity,
FineDiff::$wordGranularity,
FineDiff::$characterGranularity
);
$diff_opcodes = FineDiff::getDiffOpcodes($from_text, $to_text, $granularityStacks[$granularity]);
$diff_opcodes_len = strlen($diff_opcodes);
$exec_time = gettimeofday(true) - $start_time;
if ( $diff_opcodes_len ) {
$data_key = sha1(serialize(array('granularity' => $granularity, 'from_text' => $from_text, 'diff_opcodes' => $diff_opcodes)));
$filename = "{$data_key}{$compressed_serialized_filename_extension}";
if ( !file_exists("./cache/{$filename}") ) {
// purge cache if too many files
if ( !(time() % 100) ) {
$files = glob("./cache/*{$compressed_serialized_filename_extension}");
$num_files = $files ? count($files) : 0;
if ( $num_files > $cache_hi_water_mark ) {
$sorted_files = array();
foreach ( $files as $file ) {
$sorted_files[strval(#filemtime("./cache/{$file}")).$file] = $file;
}
ksort($sorted_files);
foreach ( $sorted_files as $file ) {
#unlink("./cache/{$file}");
$num_files -= 1;
if ( $num_files < $cache_lo_water_mark ) {
break;
}
}
}
}
// save diff in cache
$data_to_serialize = array(
'granularity' => $granularity,
'from_text' => $from_text,
'diff_opcodes' => $diff_opcodes,
'data_key' => $data_key,
);
$serialized_data = serialize($data_to_serialize);
#file_put_contents("./cache/{$filename}", gzcompress($serialized_data));
#chmod("./cache/{$filename}", 0666);
}
}
$rendered_diff = FineDiff::renderDiffToHTMLFromOpcodes($from_text, $diff_opcodes);
$from_len = strlen($from_text);
$to_len = strlen($to_text);
echo "<i>Original Text:<br></i>".$from_text."<br>";
echo $data['doc']['content'] = "<i>Edited Text<br></i>".htmlspecialchars_decode($rendered_diff);
$content = preg_replace('/<del\b[^>]*>(.*?)<\/del>/i', "", $rendered_diff);
echo '<i>New Text:</i>'.htmlspecialchars_decode(preg_replace('/<\/?ins[^>]*\>/i', "", $content));
Anyone encountered the same problem? Please help. Thank you.
I edited my script and it's working well now. Instead of passing dataString through AJAX, I passed the form data itself using data: $('form').serialize().
After several research for the createquerybuilder for mongodb, I cannot solve my issue.Can you please help me?
Here is the structure of the data :
“Field1” : { “Field2”: “value1a”,“Field3” : {“Field4” : “value2a”,”Field5” : “value3a”}}
“Field1” : { “Field2”: “value1b”,“Field3” : {“Field4” : “value2b”,”Field5” : “value3b”}}
“Field1” : { “Field2”: “value1c”,“Field3” : {“Field4” : “value2c”,”Field5” : “value3c”}}
How can I get the whole row where Field5 = value3a ?
I have proceeded with the below code but it doesn’t return me any record :
$keywords = "test";
$keywords_Array = explode(',',$keywords);
$nbKeyword = count($keywords_Array);
$odm = $this->get("doctrine mongodb");
$donnees = $odm->createQueryBuilder("MyBundle:MyCollection");
for($i=0; $i<$nbKeyword; $i++){
$search = new \MongoRegex('/"Field5":"'.$ keywords_Array [$i].'"/');
$donnees = $donnees->field("Field1")->equals(new \MongoRegex('/"Field3":"'.$search.'"/'));
}
$donnees = $donnees->getQuery()->execute();
Foreach($donnees as $ data)
{
$resp = $data->getResult();
}
Return $resp;
And another structure of data (here, the data is an array of values):
“Field1” : {“Field2”: [“value1”,”value2”,”value3”]}
How can I get the whole row where Field2 = value3 ?
It is the same as above with the below code, it doesn’t return me any record :
$keywords = "test";
$keywords_Array = explode(',',$keywords);
$nbKeyword = count($keywords_Array);
$odm = $this->get("doctrine mongodb");
$donnees = $odm->createQueryBuilder("MyBundle:MyCollection");
for($i=0; $i<$nbKeyword; $i++){
$donnees = $donnees-> field("Field1")->equals(new \MongoRegex('/"Field2":"'. $keywords_Array [$i].'"/i'));
}
$donnees = $donnees->getQuery()->execute();
Foreach($donnees as $ data)
{
$resp = $data->getResult();
}
Return $resp;
Thanks in advance
The issue is fixed.I post the solution just in case anyone has also the same problem.
For the first structure of data, the code should be like this :
$keywords = "test";
$keywords_Array = explode(',',$keywords);
$nbKeyword = count($keywords_Array);
$odm = $this->get("doctrine mongodb");
$donnees = $odm->createQueryBuilder("MyBundle:MyCollection");
for($i=0; $i<$nbKeyword; $i++){
$donnees = $donnees->field('Field1')->equals(new \MongoRegex('/"Field5":'.$keywords_Array [$i].'/'));
}
$donnees = $donnees->getQuery()->execute();
Foreach($donnees as $ data)
{
$resp = $data->getResult();
}
Return $resp;
And for the second structure of data,the code should be like this :
$keywords = "test";
$keywords_Array = explode(',',$keywords);
$nbKeyword = count($keywords_Array);
$odm = $this->get("doctrine mongodb");
$donnees = $odm->createQueryBuilder("MyBundle:MyCollection");
for($i=0; $i<$nbKeyword; $i++){
$keys = new \MongoRegex("/".$keywords_Array [$i]."/");
$donnees = $donnees->field("Field1")->in(array("Field2"=>$keys));
}
$donnees = $donnees->getQuery()->execute();
Foreach($donnees as $ data)
{
$resp = $data->getResult();
}
Return $resp;
Thank you.
I have an array containing several variables from my sql database.
{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"}, {"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}
I have an additional variable called $score that uses information from the database to calculate this score. I want to know how I can loop through and add the correct score to each country in the array.
My Original Code:
$row = $res->fetchRow();
$resGold = $row['gold'];
$resSilver = $row['silver'];
$resBronze = $row['bronze'];
$resGdp = $row['gdp'];
$resPopulation = $row['population'];
$resCountry = $row['country_name'];
$gold_score = ($resGold * $gold_value);
$silver_score = ($resSilver * $silver_value);
$bronze_score = ($resBronze * $bronze_value);
if($population == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resPopulation);
}
else if($gdp == true){
$score = (($gold_score + $silver_score + $bronze_score)/$resGdp);
}
$result = $res->fetchAll();
$result[] = array('score' => $score);
echo json_encode($result);
Your code will be something like this:
$json_data = '{"gold":"0","silver":"0","bronze":"0","gdp":"12959563902","population":"3205000","country_name":"Albania"},
{"gold":"1","silver":"0","bronze":"0","gdp":"188681000000","population":"35468000","country_name":"Algeria"}';
$countries_info_new = array();
$countries_info = json_decode($json_data);
foreach($countries_info as $country_info){
$country_info['score'] = Get_country_score($country_info['country_name']);
$countries_info_new[]=$country_info;
}
$new_json_data = json_encode($countries_info_new);