I have a table users. in this table i have a field and in that field data is something like this test,test1,test2.
I am using ajax to fetch the data from this table and show it on php file.
I am able to fetch the data but due to select2 plugin. i need to make proper formatting of this data.
fetch.php
$data = array();
while ($result->fetch()) {
$data['title'] = $title;
$data['opening'] = $opening;
$data['description'] = $description;
$data['keywords'] = $keywords;
}
echo json_encode($data);
keywords field have data something like this test,test1,test2
i need to make it in proper json format like this.
id:test text:test
id:test1 text:test1
so on.
Is it possible to make it like.
Add this code in your code (new code have comment):-
<?php
$data = array();
while ($result->fetch()) {
$data['title'] = $title;
$data['opening'] = $opening;
$data['description'] = $description;
$data['keywords'] = $keywords;
}
// code need to add
$new_data = explode(',',$data['keywords']);
$final_data = array();
foreach($new_data as $new_dat){
$final_data[] = array('id'=>$new_dat,'text'=>$new_dat);
}
echo "<pre/>";print_r( $final_data);
$data['keywords'] = $final_data; // assingnment
// print json encoded data in last
echo json_encode($data);
?>
An example code:- https://eval.in/528365
Yes you can make and two dimensional array inside empty array and $arrays = ('a' => 'b') like this then json_encode($arrays) now you get json object
Is this what are you looking for:
while ($result->fetch()) {
$data['title'] = $title;
$data['opening'] = $opening;
$data['description'] = $description;
$data['keywords'] = $keywords;
$data = array(
"id" => $data['keywords'],
"text" => $data['keywords']
);
}
echo json_encode($data);
Related
I have this class :
class MyObject{
var $title = null;
var $description = null;
var $items = [];
var $metas = [];
var $image = null;
var $country = 'Belgium';
}
And this data :
$data = new MyObject();
$data->title = 'NEW ITEM';
$data->children = ['CHILD1','CHILD2'];
$data->image = 'image.gif';
$data->country = 'Belgium';
Before storing my data in my database, I would like to remove all the defaults values from the datas, and get this output:
$dataToStore = array(
'title'=>'NEW ITEM',
'children'=>['CHILD1','CHILD2'],
'image'=>'image.gif'
);
I made an attempts with
$blank = new MyObject();
$defaults = (array)$blank;
$dataToStore = array_diff((array)$data, (array)$blank);
But it doesn't work since I get an Array to string conversion.
How could I do ?
Thanks !
Try this:
class MyObject {
public $title = null;
public $description = null;
public $children = [];
public $metas = [];
public $image = null;
public $country = 'Belgium';
protected $default = [];
function getDefault()
{
$reflect = new ReflectionClass(__CLASS__);
$vars = $reflect->getProperties(ReflectionProperty::IS_PUBLIC);
$default = [];
foreach ($vars as $privateVar) {
$default[$privateVar->getName()] = $this->{$privateVar->getName()};
}
return $default;
}
}
$data = new MyObject();
$one = $data->getDefault();
$data->title = 'NEW ITEM';
$data->children = ['CHILD1','CHILD2'];
$data->image = 'image.gif';
$data->country = 'Belgium';
$two = $data->getDefault();
echo '<pre>';
print_r($one);
print_r($two);
$output = [];
foreach($one as $key => $value){
if($value != $two[$key]){
$output[$key] = $two[$key];
}
}
print_r($output);
We get default values and set in $one
After set new data, we get default values and set in $two
Then, we check which key is not changed
First of all. Imagine that you use this class everytime you want to create a Movie entry. (I put this example because your class is very general).
class Movie{
var $title = null;
var $description = null;
var $items = [];
var $metas = [];
var $image = null;
var $country = 'Belgium';
}
Every time you want to create a new Movie record, for database or any other thing (how well have you done before).
You can create a new object.
$movie1 = new Movie();
$movie1->title = 'NEW ITEM';
$movie1->children = ['CHILD1','CHILD2'];
$movie1->image = 'image.gif';
$movie1->country = 'Belgium';
And then, if you need another one, you just have to instantiate a new object (which by default are already initialized; that's what class constructors are for) Well, we don't have a constructor here yet, but now we'll add it later
$movie1 = new Movie();
$movie1->title = 'Another title';
$movie1->items = ['SOME','ITEMS'];
$movie1->metas = ['SOME', 'METAS'];
$movie1->image = 'image.gif';
$movie1->country = 'Belgium';
$movie1->description = "Some description";
// tehere is no need for emtpy
$movie2 = new Movie();
$movie2->title = 'Title movie 2';
$movie2->items = ['SOME','ITEMS', 'MOVIE2'];
$movie2->metas = ['SOME', 'METAS', 'MOVIE"'];
$movie2->image = 'image2.gif';
$movie2->country = 'France';
$movie1->description = "Another description";
$movie1 and $movie2 now are different objects with different data.
But let's make it even better:
<?php
class Movie{
var $title;
var $description;
var $items;
var $metas;
var $image;
var $country;
function __construct($title, $description, $items, $metas, $image, $country) {
$this->title = $title;
$this->description = $description;
$this->items = $items;
$this->metas = $metas;
$this->image = $image;
$this->country = $country;
}
function GetClassVars() {
return array_keys(get_class_vars(get_class($this)));
}
}
$movie1 = new Movie("Ttile one",
"the description",
['SOME','ITEMS'],
['SOME', 'METAS'],
"image.gif",
"Belgium");
$movie2 = new Movie("Ttile two",
"the description of two",
['SOME','ITEMS', 'MORE'],
['SOME', 'METAS', 'AND MORE'],
"image2.gif",
"France");
PrintMovie($movie1);
PrintMovie($movie2);
function PrintMovie($object){
echo "#############################";
$class_vars = $object->GetClassVars();
foreach ($class_vars as $nombre) {
$val = $object->{$nombre};
if(gettype($val) == "array"){
foreach($val as $v){
echo "<pre>";
echo "\t$nombre ->";
echo " " .$v;
echo "</pre>";
}
}
else{
echo "<pre>";
echo "$nombre -> $val";
echo "</pre>";
}
}
echo "#############################\n";
}
As you are seeing in the example. I am creating two different movies (without having to delete the data each time; the constructor takes care of that, to initialize the data each time)
You also have an array with all the names of the properties of the class. In order to iterate over them and print them on the screen. You could even modify its value, since, like the PrintMovie function (it could also be called GetMovieData, if we wanted to modify it instead of printing the value)
The result of
PrintMovie($movie1);
PrintMovie($movie2);
is:
#############################
title -> Ttile one
description -> the description
items -> SOME
items -> ITEMS
metas -> SOME
metas -> METAS
image -> image.gif
country -> Belgium
############################# #############################
title -> Ttile two
description -> the description of two
items -> SOME
items -> ITEMS
items -> MORE
metas -> SOME
metas -> METAS
metas -> AND MORE
image -> image2.gif
country -> France
#############################
As you can see we have not had to delete anything and we have all the names of the properties in an array, to access them dynamically (as long as we have the object). That's why we pass it to the PrintMovie function
We could have put the print function inside the class, but I think it is also understood that way. In any case, I have invented the example so that you understand that with object-oriented programming, each object is different, therefore you do not have to delete anything to reuse it. You simply create a new object.
I am trying to get the data from an API and save it to a MySQL database. The problem is when I want to echo the data to check if it gets all the values I'm getting this error:
Notice: Trying to get property of non-object
My JSON data looks like this:
{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"},
I think this is because it is in an array. Because when I use this bit of code it gives no errors but I have to define the index of the array. What is the best way to loop through my data and put it in variables?
<?php
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = $data->AttractionInfo[0]->Id;
$attractieType = $data->AttractionInfo[0]->Type;
$attractieStatus = $data->AttractionInfo[0]->State;
$attractieStatusKleur = $data->AttractionInfo[0]->StateColor;
$attractieWachttijd = $data->AttractionInfo[0]->WaitingTime;
$attractieStatusPercentage = $data->AttractionInfo[0]->StatePercentage;
?>
I tried to find some solutions but all they use is a foreach loop. But i don't think that'll work right. Can anyone help me in the good direction or tell me how I might possibly fix this? I am not very experienced so any advice is welcome. Thanks in advance.
Update code:
require 'database-connection.php';
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = isset($data->AttractionInfo->Id);
$attractieType = isset($data->AttractionInfo->Type);
$attractieStatus = isset($data->AttractionInfo->State);
$attractieStatusKleur = isset($data->AttractionInfo->StateColor);
$attractieWachttijd = isset($data->AttractionInfo->WaitingTime);
$attractieStatusPercentage = isset($data->AttractionInfo->StatePercentage);
$sql = "INSERT INTO attracties (attractieId, attractieType, attractieStatus, attractieStatusKleur, attractieWachttijd, attractieStatusPercentage)
VALUES ('$attractieId', '$attractieType', '$attractieStatus', '$attractieStatusKleur', '$attractieWachttijd', '$attractieStatusPercentage')";
if ($db->query($sql) === TRUE) {
echo "success";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
It says 'success' but when I look into my database it inserted only empty data. I need to add all the attractions to my database so not just one row. So I need to loop through my data.
try this...
$content = json_decode(file_get_contents($url));
foreach($content->AttractionInfo as $data ){
$id = $data->Id;
$type = $data->Type;
$map = $data->MapLocation;
$state = $data->State;
$color = $data->StateColor;
if(!empty($data->WaitingTime)) {
$time = $data->WaitingTime;
}
if(!empty($data->StatePercentage)) {
$percent = $data->StatePercentage;
}
//persist your data into DB....
}
I think you need something like this:
$json = '{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"}]}';
$arr = json_decode($json);
foreach ($arr->AttractionInfo as $key => $attraction) {
foreach($attraction as $key=> $value) {
print_r($key.' - '.$value.'<br>');
$$key = $value;
}
}
echo '<br>';
echo $Id; // it will be last item/attraction id.
We can improve this code. Just say where and how do you want to use it
I am using the below code to get the ids from the pr_users table and store it in pr_notification_table,but unable to store the values separated by comma into pr_notifications table. I want to store $notification_data['show_users'] as 1,2,3,4 etc so that notifications are sent to these ids. Its inserting NULL on executing this , I have attached table images also,
pr_notifications table is as below:
My controller code is:
if($data['rows'][0]['last_status'] == 'Accepted')
{
$ids= '22';
$data['success_message'] = $this->exit_common->send_notification_to_all_roles($ids);
echo "Success";
}
My model code is:
function send_notification_to_all_roles($ids)
{
global $USER;
$post_arr = $this->input->post();
$this->db->select('g.*,id');
$this->db->from('pr_users as g');
$this->db->where('userroleid', $ids);
//$this->db->join($this->myTables['pr_users_details'].' as ud','ud.userid = g.userid');
//$this->db->join('pr_users_details as ud','ud.userid = g.userids');
/* $this->db->join($this->myTables['users_details'].' as ud','ud.userid = g.userid');
$this->db->join('pr_resignation_type as gt','gt.id = g.sr_type');*/
$query=$this->db->get();
$return = $query->result_array();
$arr = explode(',',$return);
foreach($arr as $num)
{
echo $num."<br>";
}
print_r($num);
die;
$manager_id = $this->get_value_by_id('managerid','users',$this->session->userdata('admin_id'));
$user_id='1';
$v_memberid = $manager_id . "," . $user_id;
//$manager_id = $this->get_value_by_id('managerid','users',$this->session->userdata('admin_id'));
$notification_data['ref_table'] = 'pr_resignation_requests';
$notification_data['ref_id'] = '1';
$notification_data['modifier_id'] = $USER->id;
$notification_data['show_users'] = $num;
$notification_data['notification_descr']= "A new Job has been created" ;//$manager_id;
$notification_data['notification_text'] = "A new Job has been created";
$notification_data['added_on'] = date("Y-m-d H:i:s");
$notification_data['url'] = 'exits';
$notification_data['uurl'] = 'exits';
$this->db->insert($this->myTables['notifications'],$notification_data);
return 'Resignation Request submitted successfully';
}
I think you have to get notification_id from pr_users table, and then use the following code for get notification_id comma seprated.Assume than your notification id array is :- $user_notification_ids_info
Now go with this code.
$ids = ''; $notification_ids = '';
for($i=0; $i<count($user_notification_ids_info); $i++)
{
$ids = $user_notification_ids_info[$i]['notification_id'];
$notification_ids.= $ids.", ";
}
$notification_ids = substr(trim($notification_ids), 0, -1);
Now simply echo $notification_ids; it will return your comma seprated notification id.
It will helps you try this one.
You want to store $ids comma separated? then use implode().
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(",",$arr);
I hope this will help.
I need help in converting this json data array
{"Untracked":4,"Available":3,"Groups":"4","Users":"5"}
to this type of json
[{"label":"Untracked","value":"4"},
{"label":"Available","value":"3"},
{"label":"Groups","value":"4"},
{"label":"Users","value":"5"}
]
my method is
public function graphs(){
$company_id =$this->session->userdata('itms_company_id');
$data['Untracked'] = $this->mdl_fetch->count_untracked_assets ($company_id);
$data['Available'] = $this->mdl_fetch->count_available_devices ($company_id);
$data['Groups'] = $this->mdl_fetch->count_unassigned_groups($company_id);
$data['Users'] = $this->mdl_fetch->count_unassigned_users($company_id);
echo json_encode($data);
}
Try this :
public function graphs(){
$company_id =$this->session->userdata('itms_company_id');
$data[] = array( 'label' => 'Untracked', 'value' => $this->mdl_fetch->count_untracked_assets ($company_id));
$data[] = array( 'label' => 'Available', 'value' => $this->mdl_fetch->count_available_devices ($company_id));
$data[] = array( 'label' => 'Groups', 'value' => $this->mdl_fetch->count_unassigned_groups($company_id));
$data[] = array( 'label' => 'Users', 'value' => $this->mdl_fetch->count_unassigned_users($company_id));
echo json_encode($data);
}
This is one way, but it seems a little long winded.
The json {} indicates you want an object, so you can use the simple PHP stdClass() and add the relevant properties and get the data from the array returned by your mdl->fetch's and load the object. Then just add it to the $data array.
public function graphs(){
$company_id = $this->session->userdata('itms_company_id');
$d = $this->mdl_fetch->count_untracked_assets ($company_id);
$o = new stdClass();
$o->label = 'Untracked';
$o->value = $d['Untracked'];
$data[] = $o;
$d = $this->mdl_fetch->count_available_devices ($company_id);
$o = new stdClass();
$o->label = 'Available';
$o->value = $d['Available'];
$data[] = $o;
$d = $this->mdl_fetch->count_unassigned_groups($company_id);
$o = new stdClass();
$o->label = 'Groups';
$o->value = $d['Groups'];
$data[] = $o;
$d = $this->mdl_fetch->count_unassigned_users($company_id);
$o = new stdClass();
$o->label = 'Users';
$o->value = $d['Users'];
$data[] = $o;
echo json_encode($data);
}
Here, is the example, which have same output
$a = array(); <br>
$a[0]['label'] = "Untracked"; <br>
$a[0]['value'] = "4"; <br>
$a[1]['label'] = "Available"; <br>
$a[1]['value'] = "3"; <br>
$a[2]['label'] = "Groups"; <br>
$a[2]['value'] = "4"; <br>
$a[3]['label'] = "Users"; <br>
$a[3]['value'] = "3"; <br>
$json= json_encode($a); <br>
<b>Output</b> <br>
[{"label":"Untracked","value":"4"},<br>{"label":"Available","value":"3"},<br>{"label":"Groups","value":"4"},<br>{"label":"Users","value":"3"}]<br>
So, you can write a function like this:
function graphs(){
$company_id =$this->session->userdata('itms_company_id');<br>
$data[0]["lable"] = "Untracked";<br>
$data[0]['value'] = $this->mdl_fetch->count_untracked_assets ($company_id);<br>
$data[1]["lable"] = "Available";<br>
$data[1]["value"] = $this->mdl_fetch->count_available_devices ($company_id);<br>
$data[2]["lable"] = "Groups";<br>
$data[2]["lable"] = $this->mdl_fetch->count_unassigned_groups($company_id);<br>
$data[3]["lable"] = "Users";<br>
$data[3]["lable"] = $this->mdl_fetch->count_unassigned_users($company_id);<br>
echo json_encode($data);
}
No need to change entire function.
Change from echo json_encode($data); to return json_encode($data);.
Create a function that change format from one json to another after calling a graph() function you can call another function that can return a json data as like you want
function changeFormat($js)
{
$jsArray = json_decode($js,true);
$result = array();
foreach($jsArray as $key=>$value)
{
$result[] = array("label"=>$key,"value"=>$value);
}
return json_encode($result);
}
echo changeFormat($js);
I store the field names within an array, in hopes to dynamically create the variables.
I receive a illegal offset type error for the if and else, these two lines:
$data[$tmp_field] = $tmp_field[$id];
$data[$tmp_field] = 0;
I checked the post data and it is posting with the appropriate data, but I am not sure what the problem is.
$student_id stores all the students ids., for example: $student_id = array(8,9,11,23,30,42,55);
function updateStudentInfo() {
$student_id = $this->input->post('student_id');
$internet_student = $this->input->post('internet_student');
$dismissed = $this->input->post('dismissed');
$non_matriculated_student = $this->input->post('non_matriculated_student');
$felony = $this->input->post('felony');
$probation = $this->input->post('probation');
$h_number = $this->input->post('h_number');
$office_direct_to = $this->input->post('office_direct_to');
$holds = $this->input->post('holds');
$fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');
foreach($student_id as $id):
$data = array();
foreach($fields as $field_name):
$tmp_field = ${$field_name};
if(empty($tmp_field[$id])) {
$data[$tmp_field] = 0;
} else {
$data[$tmp_field] = $tmp_field[$id];
}
endforeach;
print '<pre style="color:#fff;">';
print_r($data);
print '</pre>';
endforeach;
}
This is the array format I desire:
Array
(
[internet_student] => 1
[non_matriculated_student] => 1
[h_number] => 0
[felony] => 0
[probation] => 1
[dismissed] => 0
)
Added screenshot to give you a visual of the form the data is being posted from
foreach($student_id as $id):
$data = array();
foreach($fields as $field_name):
$tmp_field = ${$field_name};
if(empty($tmp_field[$id])) {
$data[$field_name] = 0;
} else {
$data[$field_name] = $tmp_field[$id];
}
endforeach;
print '<pre style="color:#fff;">';
print_r($data);
print '</pre>';
endforeach;
I am assuming that all these fields are arrays, as otherwise you wouldn't need any loops.
function updateStudentInfo()
{
$student_id = $this->input->post('student_id');
$internet_student = $this->input->post('internet_student');
$dismissed = $this->input->post('dismissed');
$non_matriculated_student = $this->input->post('non_matriculated_student');
$felony = $this->input->post('felony');
$probation = $this->input->post('probation');
$h_number = $this->input->post('h_number');
$office_direct_to = $this->input->post('office_direct_to');
$holds = $this->input->post('holds');
$fields = array('internet_student', 'non_matriculated_student', 'h_number', 'felony', 'probation', 'dismissed');
$student_count = count($student_id);
foreach($student_id as $id)
{
$data = array();
foreach($fields as $field)
{
if(array_key_exists($id, $$field))
$data[$field] = ${$field}[$id];
}
}
}
You are trying to use the student id as an array key for the other fields but the HTML form is just a standard indexed array, not keyed to any student data.