I can't read JSON in php - php

I have this small snippet of code in PHP to read a JSON sent by Ajax, and when I read it, the return is always empty.
<?php
$json='{"count":3,"value":[{"Code":"1","Name":"Carlos"},{"Code":"2","Name":"Charles" },{"Code":"3","Name":"Joseph"}]}';
$data = json_decode($json,true);
foreach($data as $row){
$code=$row['Code'];
$name=$row['Name'];
}
Thank You.

You were close. $data['value'] has the list of items.
foreach ($data['value'] as $row) {
print_r($row);
$code = $row['Code'];
$name = $row['Name'];
}

try foreach($data["value"] as $row) instead of foreach($data as $row)

Related

unserialising array from sql

having successfully stored my arrays by serializing them, I am having trouble unserialising amd outputting it back into arrayed data.
while( $row= $stmt->fetch(PDO::FETCH_ASSOC))
var_dump($row);
{
$rss=unserialize($row);
echo $rss;
}
var_dump($rss);
I have vardumped to try and get a better picture of what is and isnt working and unserialize not working lol..
once the data is unserialised(problem1), I can then send it through a foreach to.output it(problem 2)...?
try this:
$i=0;
while( $row= $stmt->fetch(PDO::FETCH_ASSOC))
{
foreach($row as $key=>$value)
{
$rss[$i][$key]=unserialize($value);
}
$i++;
}
var_dump($rss);

correct way to return a json_object as an array

I have an array populated using an sql statement in the following manner:
$index = 0;
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$bookname[$index] = ($row['Bookname']);
$subjectname[$index] = ($row['SubjectName']);
$index++;
}
When I go to echo json encode the Arrays I get a blank [] when I know it has been populated which is really weird.
Am I doing anything wrong in my context
echo json_encode($Bookname,$SubjectName);
You can use json_encode as like that:
<?php
$index = 0;
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$data[$index]['bookname'] = $row['Bookname'];
$data[$index]['subjectname'] = $row['SubjectName'];
$index++;
}
json_encode($data); // encode your array
?>
Try following:
$index = 0;
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$data['Bookname'][$index] = $row['Bookname']
$data['SubjectName'][$index] = $row['SubjectName'];
$index++;
}
echo json_encode($data);
You have passed two parameter while calling json_encode function. You batter combine two array in one. Then call the json_encode function like json_encode($combinedArray)

Add Object to Array while looping

One of my PDO statements returns an array. For JSON encoding I want to cast this array to an Object and append it to another array.
while($row = $sth->fetch()){
foreach($row as $key=>$value){
$r = (object) $row;
$recordArray[] = $r;
}
}
$json->record = $recordArray;
echo json_encode($json);
$recordArray seems to stay empty but it doesn't if I write $recordArray[] = "test" in the loop. So there must be something wrong with my Object $r but I can't spot the mistake. Any help is appreciated.
Here is an easier way
echo json_encode(array('record'=>$sth->fetchAll(PDO::FETCH_OBJ)));
Your foreach is wrong: in body you use object on which you iterate.
May be you mean this?
$records = [];
while($row = $sth->fetch()) {
$current = [];
foreach($row as $key => $value) {
$current[$key] = $value;
}
$records[] = $current;
}
If I understood, you want to loop over $row and add every object within $row to $recordArray.
Then you should do this:
while($row = $sth->fetch()){
foreach($row as $value){
$recordArray[] = $value;
}
}

How to format this in php side

I want to output like this
[
['Alice', 'Mike'],
['Bob', 'Jim'],
['Carol', 'Bob']
]
but i could not get the format
here is my code
$cmd = $this->connection->prepare('SELECT emp,manager from department');
$cmd->execute();
$records = $cmd->fetchAll(PDO::FETCH_ASSOC);
foreach($records as $row) {
$rowdata=$row;
}
$return_data = array($rowdata);
echo json_encode($return_data);
Thank you in advance
update: Answer
$rowdata=array_values($row);
Thank you #Ja͢ck
Try this:
$records = $cmd->fetchAll(PDO::FETCH_NUM);
foreach($records as $row) {
$rowdata[] = array_values($row);
}
If you use <pre> tags around the array and use print_r() to print it, it will come out as very readable.
Here you can check
foreach($records as $row) {
$rowdata[]=$row;
}
$return_value=array_chunk($rowdata,2);
echo json_encode($return_value);
Update :
$cmd = $this->connection->prepare('SELECT emp,manager from department');
$cmd->execute();
$records = $cmd->fetchAll(PDO::FETCH_OBJ);
$rowdata=array();
foreach($records as $record) {
$rowdata[] = array($record->em.','.$record->manager);
}
$return_data = $rowdata;
echo json_encode($return_data);

Handling PHP array of unknown size

I have the following code that should select all the users in the relevant table in my database:
$hof = mysql_query("SELECT * FROM users");
$name = array();
$website = array();
$i=0;
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
}
$i++;
I want to echo out the names and websites of all in the html section of my script (below the php) which will be a Hall of Frame of sorts. How would i do is? The fact that i do not know the size of the array deters me.
Usually, if i knew the size, i would so something like:
<?php echo $name[1];?>
<?php echo $name[2];?>
//and so on
Many thanks in advance. P.S. I plan to move across to MySQLi when i have the functionality of the website sorted first on localhost. Cheers
Your $i++; statement should be inside while loop
while($result = mysql_fetch_array($hof)){
$name[$i] = $result['company'];
$website[$i] = $result['website'];
$i++;
}
Better You do it like this,
$rows = array();
while($result = mysql_fetch_assoc($hof)){
$rows[] = $result;
}
and you echo them like this,
<?php
$len = count($name);
for($i=0;$i<$len;$i++){
echo $name[1];
}
?>
And for the alternative method use this,
<?php
foreach($rows as $row){
echo $row['name']; // use $row['website'] to echo website.
}
?>
foreach($name as $key=>$value){
echo $name[$key];
echo $website[$key];
}
Also there no need to take $i++, you can use following way
while($result = mysql_fetch_array($hof)){
$name[] = $result['company'];
$website[] = $result['website'];
}
See array in manual
First off the $i++ should be inside the loop.
To output them all, you could use implode(), or maybe foreach.
First, take your data into array
$data = array();
$sql = "SELECT * FROM users";
$res = mysql_query($sql) or trigger_error(mysql_error()."[$sql]");
while($row = mysql_fetch_array($res)){
$data[] = $row;
}
then use it anywhere you wish, say, in the template:
<ul>
<? foreach($data as $row): ?>
<li><?=$row['company']?></li>
<? endforeach ?>
</ul>
How about:
foreach ($name as $val)
{
echo $val;
}
you can use mysql_num_rows() to know the number of results returned by your query
$arrarySize = mysql_num_rows($hof);

Categories