JQuery AJAX calling PHP Fine Diff result gives wrong value - php

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().

Related

Using an If statement in PHP but not working

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, "'", " ");

Catch Tweets with JSON and sort by likes?

I am currently running a wordpress backend and want to display some tweets based on hastags on my website. For the general API request and database storage, I use this function:
private function parseRequest($json) {
$tmp = $json;
$result = array();
if (isset($json['statuses'])) {
$tmp = $json['statuses'];
}
if (isset($tmp) && is_array($tmp)){
foreach ($tmp as $t) {
$this->image = null;
$this->media = null;
$tc = new \stdClass();
$tc->feed_id = $this->id();
$tc->id = $t['id_str'];
$tc->type = $this->getType();
$tc->nickname = '#'.$t['user']['screen_name'];
$tc->screenname = (string)$t['user']['name'];
$tc->userpic = str_replace('.jpg', '_200x200.jpg', str_replace('_normal', '', (string)$t['user']['profile_image_url']));
$tc->system_timestamp = strtotime($t['created_at']);
$tc->text = $this->getText($t);
$tc->userlink = 'https://twitter.com/'.$t['user']['screen_name'];
$tc->permalink = $tc->userlink . '/status/' . $tc->id;
$tc->media = $this->getMedia($t);
#$tc->additional = array('shares' => (string)$t['retweet_count'], 'likes' => (string)$t['favorite_count'], 'comments' => (string)$t['reply_count']);
if ($this->isSuitablePost($tc)) $result[$tc->id] = $tc;
}
}
return $result;
}
Now I am looking for a function that counts all the variable in the "additional array together e.g. shares + likes + comments and sorts all posts based on the resulting number.
I am using the standard wordpress sql database. I cannot find a solution or I am just blind.
Thanks in regards
You could use a simple usort function:
usort($tc, function($a, $b) {
$a_sum = array_sum($a->additional);
$b_sum = array_sum($b->additional);
if ($a_sum == $b_sum) {
return 0;
}
return ($a_sum < $b_sum) ? -1 : 1;
});

getting error to display all record in php json

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

Parse Json Encode Array PHP error

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.

PHP Array Nominal Indexes with Strings

I have a PHP application that takes a CSV in input; in the first column I have both category and subcategory splitted by a '|'. I have to put this stuff in a Open Cart DB, which has the same table for Category and Subcategory (a column "parent_id" indicates the category_id of the Category).
I thought to build a class with all the fields needed as follows:
class Categorie {
public $category_id;
public $parent_id;
public $image;
public $top;
public $column;
public $sort_order;
public $status;
public $date_modified;
public $date_added;
public $language_id;
public $name;
public $description;
public $meta_description;
public $meta_keywords;
}
Then I analyze the data:
$categorie = array();
while ( ( $riga_file = fgetcsv( $file, 100000, "\t" ) ) !== false )
{
$array_el = count( $riga_file );
for( $el_cur = 0; $el_cur < $array_el; $el_cur++ )
{
switch ( $el_cur )
{
case 0:
$colonne = explode( "|", $riga_file[$el_corr] );
$categoria = new Categorie();
$categoria->image = "";
$categoria->top = 1;
$categoria->column = 1;
// ... bla adding description data
if( $categorie[$colonne[0]] == NULL ) // (1)
{
$categoria->name = $colonne[0];
$categoria->category_id = $id_categoria;
$categoria->parent_id = 0;
$categorie[$colonne[0]] = $categoria;
$id_categoria++;
}
if( $colonne[1] != NULL ) // (2)
{
$categoria->name = $colonne[1];
if( $categorie[$colonne[1]] == NULL )
{
$categoria->category_id = $id_categoria;
$categoria->parent_id = $categorie[$colonne[0]]->category_id;
$categorie[$colonne[1]] = $categorie;
$id_categoria++;
}
}
break;
}
I should have an array filled with a collection of unique objects like:
// OUT(3)
Category 1
Subcategory 1
Category 2
Subcategory 2...
If I put echoes of $categoria (not $categorie) inside (1) and (2), I see exactly what I wrote down in OUT(3), which leads me to think that my "engine" is correct. The problems come when I try to search into the array:
echo "<table border='1'>";
foreach( $categorie as $value )
{
echo "<tr>
<td>$value->category_id</td>
<td>$value->parent_id</td>
<td>$value->name</td>
</tr>";
}
echo "</table>";
because I don't get Categories at all, and most but not all Subcategories.
Am I doing something wrong with "search engine" or I misunderstood something with PHP Arrays (probably because I come from C++ and this php is f**king my mind)?
I solved the problem, or better: problems.
1) I mispelled a variable: in (2) I wrote:
$categorie[$colonne[1]] = $categorie;
The correct writing is:
$categorie[$colonne[1]] = $categoria;
2) The bigger problem was from my "unknowing" of PHP, in fact, fixed the problem 1, I got an output like:
subcategory1
subcategory1
subcategory2
subcategory2
and so on. This lead me to guess that when I do:
$categorie[$colonne[1]] = $categoria;
PHP doesn't copy the values inside, but uses addresses instead. Follows the right code:
switch ( $el_corr )
{
case 0: // Categorie e sottocategorie
$colonne = explode( "|", $riga_file[$el_corr] );
$categoria = new Categorie();
$categoria->image = "";
$categoria->top = 1;
$categoria->column = 1;
$categoria->sort_order = 0;
$categoria->status = 1;
// Category_Description Campi
$categoria->language_id = 1;
$categoria->name = $colonne[0];
$categoria->description = "";
$categoria->meta_description = "";
$categoria->meta_keywords = "";
////////////////////////
if( $categorie[$colonne[0]] == NULL )
//if( !trova_categorie( $colonne[0], $categorie ) )
{
$categoria->name = $colonne[0];
$categoria->category_id = $id_categoria;
$categoria->parent_id = 0;
$categorie[$colonne[0]] = $categoria;
$id_categoria++;
}
$categoria = new Categorie();
$categoria->image = "";
$categoria->top = 1;
$categoria->column = 1;
$categoria->sort_order = 0;
$categoria->status = 1;
// Category_Description Campi
$categoria->language_id = 1;
$categoria->name = $colonne[0];
$categoria->description = "";
$categoria->meta_description = "";
$categoria->meta_keywords = "";
if( $colonne[1] != NULL )
{
$categoria->name = $colonne[1];
if( $categorie[$colonne[1]] == NULL )
//if( !trova_categorie( $colonne[1], $categorie ) )
{
$categoria->category_id = $id_categoria;
$categoria->parent_id = $categorie[$colonne[0]]->category_id;
$categorie[$colonne[1]] = $categoria;
$id_categoria++;
}
}
break;
}

Categories