i am having a json string like:
[
{
"message": "Test+sms",
"sender": "test",
"billcredit": "0.00",
"messageStatus": "DND",
"sendondate": "2015-04-22 15:22:00",
"provider": "aaaa"
},
{
"message": "Test+sms",
"sender": "test",
"billcredit": "0.00",
"messageStatus": "DND",
"sendondate": "2015-04-22 15:22:00",
"provider": "aaa"
},
{
"message": "Test+sms",
"sender": "test",
"billcredit": "1.00",
"messageStatus": "DELIVRD",
"sendondate": "2015-04-22 15:22:00",
"provider": "aaaa"
},
{
"message": "Test+sms",
"sender": "test",
"billcredit": "1.00",
"messageStatus": "DND REJECTED",
"sendondate": "2015-04-22 15:22:00",
"provider": "aaaa"
}
]
I try doing like this:
$objs = json_decode($data,true);
foreach ($objs as $obj){
$repor= $obj['messageStatus'];
echo $repor;
But its not working. Please anybody can help me to get rid out of this. Please help me to upload $repor sequentially in mysql.
Working Fine Now Check
$data='[{"message":"Test+sms","sender":"EXECUT","billcredit":"0.00","messageStatus":"DND","sendondate":"2015-04-22 15:22:00","provider":"aaaa"},{"message":"Test+sms","sender":"EXECUT","billcredit":"0.00","messageStatus":"DND","sendondate":"2015-04-22 15:22:00","provider":"aaa"},{"message":"Test+sms","sender":"EXECUT","billcredit":"1.00","messageStatus":"DELIVRD","sendondate":"2015-04-22 15:22:00","provider":"aaaa"},{"message":"Test+sms","sender":"EXECUT","billcredit":"1.00","messageStatus":"DND REJECTED","sendondate":"2015-04-22 15:22:00","provider":"aaaa"}]';
$objs = json_decode($data, true);
foreach ($objs as $obj){
$repor= $obj['messageStatus'];
echo $repor." ";
}
I have placed only single quotation around json array. Nothing more.
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
Looks like it's almost json, but not quite.
Try this:
$data = '{"messages":' . $data . '}';
$decoded = json_decode($data, true);
foreach ($decoded['messages'] as $message) {
$messageStatus = $message['messageStatus'];
echo $messageStatus;
}
Related
My goal is: I would like to use datatable with multiple filtering options. for this purpose all files should be separated from each other (means that there is an html, js, php file) and read from a database. however, with my current code in js i get the error message:
ReferenceError: $ is not defined
I'm new in this area, could someone have found a suitable manual for my application? everything on the internet has been coded into one or two files. I use also smarty.
My Files:
test.php
<?php
require_once './Smarty/libs/Smarty.class.php';
echo "<script src=\"javascripts/test.js?v=3\" type=\"text/javascript\"></script>";
echo "<script src=\"javascripts/jquery.js?v=3\" type=\"text/javascript\"></script>";
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css\">";
$smarty = new Smarty();
$smarty->display('test.tpl');
test.js
$(document).ready(function() {
$('#datatables-table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "testHelper.php?action=listmovies",
type: "post",
datafilter: function(data){
var json = jQuery.parseJSON(data);
if (json.error){
console.log(json.error);
}
}
},
columns: [
{"data": "test", "name": "test", "title": "Test"},
{"data": "test2", "name": "test2", "title": "Test2"},
]
});
} );
test.tpl
<main class="content">
<table id="datatables-table" class="table table-striped table-hover" style="width:100%"></table>
</main>
testHelper.php
<?php
if($_REQUEST['action'] == "listmovies"){
$data = array();
$value['test1'] = utf8_encode("test1");
$value['test1'] = utf8_encode("test1");
$data[] = $value;
$value2['test2'] = utf8_encode("test2");
$value2['test2'] = utf8_encode("test2");
$data[] = $value2;
$return['data'] = $data;
echo json_encode($return);
}
I have no idea how i do this, i have some pieces of code, that i need to "handle" and use in javascript for some search engine
This is what i have in my database
[
["Reparation", "Pris"],
["Fejlfinding", "Gratis"],
["Udskiftning af Skærm (Refurbished)", "3699,-"]
]
This is what i need it to look like after i get it from the database and it has been handled.
var searchChoices = {
"Name": {
"Model Name": {
"icons": {
"dark": "Imagelink",
"light": "imagelink"
},
"items": [
{
"headline": "Gratis",
"text": "Fejlfinding"
},
{
"headline": "3699",
"text": "Udskiftning af Skærm (Refurbished)"
}
]
}
}
};
I have really no idea how to do this? I don't even know what it's called.
Can someone please help me, or point me in the right way?
Thanks
I think you should use php json_encode function to send data to javascript. You can make something like this:
<script>
var data = <?=json_encode($data);?>
...
Next step is simple loop to add items:
for(var row in data)
searchChoices["Name"]["Model name"].items.push({
"headline": data[row][1],
"text": data[row][0]
});
You can also generate whole javascript object using PHP:
<script>
var searchChoices = {
"Name": {
"Model Name": {
"icons": {
"dark": "Imagelink",
"light": "imagelink"
},
"items": [
<?php
foreach($data as $row)
echo '{"headline": "' . $row[1] . '", "text": "' . $row[0] . '"},';
?>
]
}
}
};
OK, this is another solution, regular expression:
(\[\"(.+)\"\,\ ?\"(.+)\"\]\,?)
The next step is to get data from preg_match_all result.
This is simple script i wrote to test:
<?php
$data = <<<JS
[
["Reparation", "Pris"],
["Fejlfinding", "Gratis"],
["Udskiftning af Skærm (Refurbished)", "3699,-"]
]
JS;
$pattern = '/(\[\"(.+)\"\,\ ?\"(.+)\"\]\,?)/';
$matches = [];
$result = preg_match_all($pattern, $data, $matches);
for($i=0, $j=count($matches[2]); $i<$j; $i++) {
echo '{"headline": "' . $matches[3][$i] . '", "text": "' . $matches[2][$i] . '"},' . "\n";
}
I am trying to read from a JSON file into a PHP array and then echo the array's content, so I can fetch the info with ajax in javascript and convert the array in javascript to an array of JSON objects.
Here is how my JSON file looks like.
[["{\"id\":1474541876849,\"name\":\"D\",\"price\":\"12\"}"],["{\"id\":1474541880521,\"name\":\"DD\",\"price\":\"12\"}"],["{\"id\":1474541897705,\"name\":\"DDDGG\",\"price\":\"124\"}"],["{\"id\":1474541901141,\"name\":\"FAF\",\"price\":\"124\"}"],["{\"id\":1474543958238,\"name\":\"tset\",\"price\":\"6\"}"]]
Here is my php :
<?php
$string = file_get_contents("products.json");
$json_a = json_decode($string, true);
$arr = array();
foreach ($json_a as $key) {
array_push($arr,$key[0]);
}
foreach ($arr as $key) {
echo $key;
}
?>
And this is what I am getting on the client side :
{"id":1474541876849,"name":"D","price":"12"}{"id":1474541880521,"name":"DD","price":"12"}{"id":1474541897705,"name":"DDDGG","price":"124"}{"id":1474541901141,"name":"FAF","price":"124"}{"id":1474543958238,"name":"tset","price":"6"}
It looks like I am not that far, but what can I do so I can actually make this a JSON object?
Please help!
The problem is that you have JSON inside JSON.
you have to decode twice:
<?php
$string = file_get_contents("products.json");
$json_a = json_decode($string, true); //here you turn a JSON-string into an array containing JSON-strings
$arr = array();
foreach ($json_a as $key) {
array_push($arr,json_decode($key[0],true)); //and here you turn each of those JSON-strings into objects themselves
}
echo json_encode($arr);
gives me this:
[{
"id": 1474541876849,
"name": "D",
"price": "12"
}, {
"id": 1474541880521,
"name": "DD",
"price": "12"
}, {
"id": 1474541897705,
"name": "DDDGG",
"price": "124"
}, {
"id": 1474541901141,
"name": "FAF",
"price": "124"
}, {
"id": 1474543958238,
"name": "tset",
"price": "6"
}]
which is valid JSON itself and probably what you want.
I want to display data(json) in my site using AngularJs . here's what i did :
Create a database in phpmyAdmin .
Create a table with 2 row , subject and body . Should i create an id ?
After doing with PHP and angular , I got JSON like this :
[{
"0":"Soheil","subject":"Soheil",
"1":"Sadeghbayan","body":"Sadeghbayan"}
,{"0":"","subject":"","1":"","body":""}
,{"0":"","subject":"","1":"","body":""}
,{"0":"dasdasd","subject":"dasdasd","1":"qe","body":"qe"}
,{"0":"Hello","subject":"Hello","1":"This is chandler !","body":"This is chandler !"}
,{"0":"","subject":"","1":"","body":""},
{"0":"Something new in website","subject":"Something new in website","1":"oh Awsome !","body":"oh Awsome !"
}]
I think this is invalid JSON because when I replace it with custom JSON that I wrote it work .
Json valid
{
"fruits": [
{
"id": "1",
"name": "Apple"
},
{
"id": "2",
"name": "Orange"
}
]
}
AngularJS
var fruitsApp = angular.module('fruitsApp', []);
fruitsApp.factory('fruitsFactory', function($http) {
return {
getFruitsAsync: function(callback) {
$http.get('fruits.json').success(callback);
}
};
});
fruitsApp.controller('fruitsController', function($scope, fruitsFactory) {
fruitsFactory.getFruitsAsync(function(results) {
console.log('fruitsController async returned value');
$scope.fruits = results.fruits;
});
});
Html
<ul>
<li ng-repeat="fruit in fruits">
{{fruit.subject}} is {{fruit.body}}
</li>
</ul>
php
include('config.php');
$data = json_decode(file_get_contents("php://input"));
$subject = mysql_real_escape_string($data->subject);
$body = mysql_real_escape_string($data->body);
mysql_select_db("angular") or die(mysql_error());
mysql_query("INSERT INTO newstory (subject,body) VALUES ('$subject', '$body')");
Print "Your information has been successfully added to the database.";
$query = "SELECT * FROM newstory";
$result = mysql_query($query);
$arr = array();
while ($row = mysql_fetch_array($result)) {
$subject = $row['subject'];
$body = $row['body'];
$arr[] = $row;
}
echo json_encode($arr);
Any idea ? Thx in advance
Your JSON is a valid. Refer to this for information on JSON and this to check/validate a JSON object.
The data coming back from your $http.get / database data does not have a fruits attribute and you expect that when you set your $scope.fruits (the below snippet is taken from your code):
$scope.fruits = results.fruits;
The structure of the data that is being returned by the $http.get call is different than the format of your sample data.
Here's your $http.get / database data (I shortened it for brevity):
[
{
"0": "Soheil",
"1": "Sadeghbayan",
"subject": "Soheil",
"body": "Sadeghbayan"
},
{
"0": "Hello",
"1": "This is chandler !",
"subject": "Hello",
"body": "This is chandler !"
},
{
"0": "",
"1": "",
"subject": "",
"body": ""
}
]
And here's your sample / mock data:
{
"fruits": [
{
"id": "1",
"name": "Apple"
},
{
"id": "2",
"name": "Orange"
}
]
}
The former is an array of objects with keys: 0, 1, subject and body.
The latter is an object with keys: fruits.
They are both valid JSON objects with different object structures. But, you expect a fruits attribute where there isn't one. Also, your HTML/UI might be expecting the data format to look like what is in your mock data. So check that too.
I am using twitterapi to get the friends list in php and I have encoded the result as a json array, but I cannot parse the json array in javascript.I have validated the json array produced by the php and its a valid json array. Below is my code.
php
$friends = array();
$friend_list = array();
$myfriend = array();
$connection = new TwitterOAuth($CONSUMER_KEY, $CONSUMER_SECRET,oauth_token,oauth_token_secret);
$friends =$connection->get("https://api.twitter.com/1.1/friends/list.json?cursor=-1&screen_name=twitterapi&skip_status=true&include_user_entities=false&count=200);
foreach($friends as $friend) {
if(!empty($friend))
{
foreach($friend as $value)
{
$friend_list['id']=$value->id;
$friend_list['screen_name']= $value->screen_name;
$friend_list['name']= $value->name;
$friend_list['profile_image_url']= $value->profile_image_url;
$friend_list['location']= $value->location;
array_push($myfriend, $friend_list);
}
}
}
$newarray = json_encode($myfriend);
'
javascript
<script>
var obj1 = JSON.parse('<?php echo $newarray ;?>');
console.log(obj1); // am not getting anything in console
</script>
EDITED
output from echo $newarray;
[
{
"id": 50393960,
"screen_name": "BillGates",
"name": "Bill Gates",
"profile_image_url": "http://pbs.twimg.com/profile_images/1884069342/BGtwitter_normal.JPG",
"location": "Seattle, WA"
},
{
"id": 141527741,
"screen_name": "prakashraaj",
"name": "Prakash Raj",
"profile_image_url": "http://pbs.twimg.com/profile_images/2951815972/ab32fb806b480d0dc761805ae4ef9775_normal.jpeg",
"location": "india"
},
{
"id": 88856792,
"screen_name": "aamir_khan",
"name": "Aamir Khan",
"profile_image_url": "http://pbs.twimg.com/profile_images/2254031972/_MG_2190_normal.jpeg",
"location": "Mumbai"
},
{
"id": 107318424,
"screen_name": "bipsluvurself",
"name": "Bipasha Basu",
"profile_image_url": "http://pbs.twimg.com/profile_images/419745345178832896/8JvqwEM9_normal.jpeg",
"location": "Mumbai, India"
}
]
Please help, am stuck with this
You can directly output the json:
Change to:
var obj1 = <?php echo $newarray ;?>;
For example:
<?php
$newarray = json_encode(array('name' => 'srain'));
?>
var obj1 = <?php echo $newarray ;?>;
It will output:
var obj1 = {"name":"srain"};
update
If your js script is not in the same file with the php code, the $newarray will be null.
In the absence of information about how you validated json array, this is what I can recommend. Change your javascript to:
<script>
var jsonString = '<?php echo $newarray ;?>';
console.log(jsonString);
var obj1 = JSON.parse(jsonString);
console.log(obj1); // am not getting anything in console
</script>
You can see the content of jsonString in the javascript console. That should give you hints about what is going wrong.
Note:You are fetching JSON content from twitter, converting it to PHP data structure and converting it back to JSON. Sending the JSON string from twitter to javascript is far more efficient - if there is no need to filter/alter the twitter returned data.