how to convert objects to an array of arrays in php? - 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.

Related

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
}

PHP PDO retrieving json array from database - removing unwanted chars

I am storing a JSON array of data within a row in a database and attempting to retrieve the array in order to use in a foreach loop.
The code below is the code that I will be using for the foreach loop, but I am having some troubles actually retrieving the data, using PDO, as needed to be used.
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $data){
echo $data['id'];
}
The problem I am having is retrieving the array to put into $data using PDO. Currently I have this query and code, the output for which is below.
$statement = $this->db_connection->prepare("SELECT gp FROM gs WHERE c_s= :c_s");
$statement->bindParam(':c_s', $c_s);
$statement->execute();
$data = $statement->fetchAll();
$result = json_encode($data, true);
return $result;
Mixed with the following code to show the array:
foreach ($result as $key) {
echo $key['id'];
}
print_r($result);
die();
This gives an error for the for each, and outputs the array (unusable) as following:
[{"gp":"[{\"id\":\"H592736029375\"},{\"id\":\"K235098273598\"},{\"id\":\"B039571208517\"}]","0":"[{\"id\":\"H592736029375\"},{\"id\":\"K235098273598\"},{\"id\":\"B039571208517\"}]"}]
Being as the first segment of code I have I can use the data as I needed I'm just in need of some guidance of how to correctly get the array from the database to then be used in the foreach.
I'm aware that I'm currently using json_encode instead of json_decode, using json_decode gives the following error:
Warning: json_decode() expects parameter 1 to be string, array given
Suggestions for my errors would be much appreciated
fetchAll() returns an array of rows, not the single field you expect:
$statement = $this->db_connection->prepare("SELECT gp FROM gs WHERE c_s= :c_s");
$statement->bindParam(':c_s', $c_s);
$statement->execute();
$rows = $statement->fetchAll();
$data = $rows[0]['gp'];
$result = json_decode($data);
You are expecting $data to be a string while it's an array. Either use $statement->fetchColumn() to retreive a single field or use json_decode($data['gp'])
Other then that, I'm not exactly sure why you are looping over a json_encoded array, you can't do that.
json_encode() formats variables for javascript object notation.
json_decode() loads variables from strings(READ: string, not array) in the javascript object notation.
To make it even clearer:
use json_encode() to insert data in mysql.
use json_decode() to put back a column to their corresponding php variable/state.

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/

Associative array decoding in JSON

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.

PHP, JSON, and MySQL

What is the easiest way to retrieve data from the database, and convert the data to a JSON String?
Is there any kind of helper class? or am I supposed to loop through the columns in my dataset to create the JSON string?
You can use the json_encode function to convert a native PHP array or stdClass object to it's corresponding JSON representation:
$result = $db->query('SOME QUERY');
$set = array();
if($result->num_rows) {
while($row = $result->fetch_array()) {
$set[] = $row;
}
}
echo json_encode($set);
Make an array from mySQL, and json_encode() it
Yes, use PHP's functions to handle JSON encoding.
Here's an example I got from this SO question:
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
Have you seen the json_encode() function? It takes an array as input and outputs JSON. So the most basic would be a two-dimensional array representing your table as input to json_encode
If you use the json_encode function then you're depending on somebody else's interpretation of the right way to format the json. Which means that you might come out with weird json, or have to contort your classes in evil ways to make the json come out right.
Just something to think about.

Categories