Associative array decoding in JSON - php

I am trying to change the class of a list of elements based on information in a DB. I figure the easy way was via an array. I build the array on the php side as follows.
$setClassResult = array();
while($row = mysql_fetch_array( $result ))
{
$setClassResult= array_push_assoc($setClassResult, $row['item_id'], $row['parent']);
}
echo json_encode(array($setClassResult));
break;
which give me....
[{"830":"0","734":"830","733":"830","732":"830","735":"830","737":"830","736":"830","738":"830","739":"830","740":"830","741":"830","742":"830","872":"0","869":"872","868":"872","880":"872","964":"872"}]
to decode and change the elements I use.....
$.each(data, function(key, val) {
$("#recordsArray_"+key).toggleClass(val);
alert(key+" "+val);
});
The alert happens once with 0[object,Object] Is this because of the way I created the array? The first thing I notice wrong is the [ and ] around the JSON.

No need to add extra array, try with :
echo json_encode($setClassResult);

Your result is in array of object format:
[{"830":"0","734":"830","733":"830","732":"830","735":"830","737":"830","736":"830","738":"830","739":"830","740":"830","741":"830","742":"830","872":"0","869":"872","868":"872","880":"872","964":"872"}]
So when you iterate, it iterates through array first & says key is 0 & value is an object.so, if you later iterate through value which is an object, you will get it
or as soju if u dont require to store it in array of objects but a single object & iterate once.

Related

PHP JSON Arrays within an Array

I have a script that loops through and retrieves some specified values and adds them to a php array. I then have it return the value to this script:
//Returns the php array to loop through
$test_list= $db->DatabaseRequest($testing);
//Loops through the $test_list array and retrieves a row for each value
foreach ($test_list as $id => $test) {
$getList = $db->getTest($test['id']);
$id_export[] = $getList ;
}
print(json_encode($id_export));
This returns a JSON value of:
[[{"id":1,"amount":2,"type":"0"}], [{"id":2,"amount":25,"type":"0"}]]
This is causing problems when I try to parse the data onto my android App. The result needs to be something like this:
[{"id":1,"amount":2,"type":"0"}, {"id":2,"amount":25,"type":"0"}]
I realize that the loop is adding the array into another array. My question is how can I loop through a php array and put or keep all of those values into an array and output them in the JSON format above?
of course I think $getList contains an array you database's columns,
use
$id_export[] = $getList[0]
Maybe can do some checks to verify if your $getList array is effectively 1 size
$db->getTest() seems to be returning an array of a single object, maybe more, which you are then adding to a new array. Try one of the following:
If there will only ever be one row, just get the 0 index (the simplest):
$id_export[] = $db->getTest($test['id'])[0];
Or get the current array item:
$getList = $db->getTest($test['id']);
$id_export[] = current($getList); //optionally reset()
If there may be more than one row, merge them (probably a better and safer idea regardless):
$getList = $db->getTest($test['id']);
$id_export = array_merge((array)$id_export, $getList);

read jquery array in php

i am trying to retrieve the value of array via post in php script.
var data = [];
table.rows({ selected: true }).every(function(index){
// Get and store row ID
data.push(this.data()[0]); //create a 1 dimensional array
});
//send data via ajax
$.ajax({
url: '/...../...',
type: 'POST',
data: {userid:data},
dataType: 'json',
In my PHP script so far I am unable to decode the array. Have tried many ways
$myArray = $_REQUEST['userid'];
foreach ($arr as $value) {
$userid= $value; //for now just trying to read single item
}
I have tried print_r($myArray ); this sucessfully prints array contents to screen.
I am trying to retrieve the values for processing! Kindly point me in the right direction
I don't think that PHP would recognise the array that you've called "data" as being an array. Couldn't you turn the data from your table rows into values in a JavaScript object, encode it as a JSON string, then post that to your PHP script and use json_decode($_POST["userid"]) on the PHP end to convert it into a PHP array.
The object you are posting to PHP isn't in particular a jQuery object. Instead it is an JSON object or rather a JSON string. I guess you can't read that object the way you would read an regular array in PHP.
You might want to try to decode the string with json_decode(). With true as an function argument, it will return an php array as suggested in this stackoverflow answer https://stackoverflow.com/a/6964549/6710876
$phpArray = json_decode($myArray, true);
Documentation of json_decode(): http://php.net/manual/en/function.json-decode.php
simply use:
echo json_encode($myArray);
You're foreach is looping $arr, which doesn't exist. Your array is being set to $myArray, so use that in your for.
$myArray = $_REQUEST['userid'];
foreach ($myArray as $value) {
$userid= $value; //for now just trying to read single item
}
I believe you should also be able to find your values in $_POST
According to your var_dump :
array(1) { ["userid"]=> string(21) "assssssss,camo,castor" }
and if we assume "assssssss,camo,castor" are 3 different usernames.
You should use this:
$userids=explode(",",$myArray->userid);
foreach($userids as $userid){
// use $userid
}

Loop Through PHP Array Encoded In JSON

I have a PHP array that has a table id as the key and a table field as the value.
Example PHP:
while($row = mysql_fetch_array($result))
{
$id = $row['id'];
$array[$id] = $row['some_field'];
}
I then use json_encode($array) to get something like:
{"id1":"value1","abc":"123","xyz":"789"}
How can I loop through this in jQuery? From what I have found so far it seems like I need to know the key. So:
var obj = jQuery.parseJSON(jsonVar);
alert(obj.abc); //prints 123
But how can I get these values if I don't know the keys since they are dynamic?
Do I need to restructure my PHP array?
Once you encode an associative array in php into a JSON object it is no longer an array, it is an object with keys and values. You can iterate through them in javascript using for..in
for (var key in obj) {
console.log(obj[key]);
}
Note: for..in does not garuntee order, if you need to ensure order you will have to make your array indexed, instead of key=>value, and use a for loop (or while) instead.
You can get the keys of your array using Object.keys, then loop through them. Unlike for...in, this gives you the option to .sort() the keys before processing them:
var keys = Object.keys(obj).sort(); // sorting is optional
for (var i=0; i<keys.length; i++) {
var key = keys[i],
val = obj[key];
console.log(key+":"+val);
};
In older browsers, you'll need a polyfill to enable the Object.keys method. MDN has one on their documentation page.

json encoding 2 dimension array

I have the following in php:
$query = mysql_query($sql);
$rows = mysql_num_rows($query);
$data['course_num']=$rows;
$data['course_data'] = array();
while ($fetch = mysql_fetch_assoc($query) )
{
$courseData = array(
'course_name'=>$fetch['course_name'],
'training_field'=>$fetch['training_field'],
'speciality_field'=>$fetch['speciality_field'],
'language'=>$fetch['language'],
'description'=>$fetch['description'],
'type'=>$fetch['type'],
);
array_push($data['course_data'],$courseData);
}
echo json_encode($data);
when I receive the result of this script in jquery (using post)
I log it using :
console.log(data['course_data']);
and the output is :
[Object { course_name="Introduction to C++", training_field="Engineering" , speciality_field="Software", more...}]
But I can't seem to figure out how to access the elements.
I tried
data['course_data'].course_name
data['course_data']['course_name']
Nothing worked. Any ideas
When you array_push($data['course_data'],$courseData); you are actually putting $courseData at $data['course_data'][0] and therefore you would access it in JavaScript as data['course_data'][0]['course_name'].
If you only intend to have one result, instead of array_push($data['course_data'],$courseData); you should just specify $data['course_data'] = $courseData. Otherwise, you should iterate over data['course_data'] like so:
for (i in data['course_data']) {
console.log(data['course_data'][i]['course_name']);
}
You should specify the index in the first array for instance
data['course_data'][0]['course_name'];
you could make it better if you had defined the first array just as variable not a variable within an array
$data['course_data'][0]['course_name']
should do the trick. If not please send the output of var_dump($data)
Assuming the PHP code is correct, you will receive a JSON data like:
{
"course_num":34,
"course_data":[
{
"course_name":"name_value",
....
},
....etc (other object based on SQL result)
]
}
So, if you want to access to the total number of result:
data.course_num
If you want to access to the first element of the list of result:
data.course_data[0]
If you want to access to the name of the first element of the list of result:
data.course_data[0].course_name
or
data.course_data[0]['course_name']
use jquery's parseJSON method to get all the goodies out of the json object...
http://api.jquery.com/jQuery.parseJSON/

how to convert objects to an array of arrays in php?

I have a jQuery post that returns some objects.
So, I have a DB query result that I do json_encode($result) and then I send it as a response in the success function inside the jQuery post.
If I console.log the response I see multiple objects. What I want is to send the response as an array of arrays.
In PHP
json_encode($results)
In javascript:
success: function(json) {
console.log(json);
}
In console log:
[>Object , >Object , >Object]
Any ideas?
Your $results in php is an array of objects or of associative arrays. Make it an array of numerically-indexed arrays before you send with casting:
// ASSUMING each $result object does not have its own nested arrays
foreach ($results as &$result) {
$result = array_values((array) $result);
}
Note you will lose the ability to get items by column name.
But please step back and think about where your $result comes from.
If you are using mysql driver, consider doing this when building your result:
$results = array();
// Note we use MYSQL_NUM option, so $row looks like array('col1value', 'col2value')
while (FALSE !== ($row = mysql_result_array($resource, MYSQL_NUM))) {
$results[] = $row;
}
json_encode($results);
In Javascript with JQuery:
jQuery.makeArray();
http://api.jquery.com/jQuery.makeArray/
In php, casting:
$aArray = (array) $oObject;
json encode will encode a string as a json OBJECT which in javascript is an object. in javascript an array is simply an object with special helper functions. there shouldn't be a need to create an array from the object as you can manipulate an object as easily as you can manipulate an array.

Categories