How to format this in php side - php

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);

Related

I can't read JSON in 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)

PHP Echo json_encode

I am having a small problem, I am showing json using PHP, I have this code:
foreach($result as $r){
$returnEcho["Id"] = $r["id"];
$returnEcho["Username"] = $r["username"];
$returnEcho["Email"] = $r["email"];
$returnEcho["Info"] = $r["Info"];
echo json_encode($returnEcho);
The problem with this code is, it will display the JSON like this:
{"Username":"X","Email":"X","Info":"X"}
{"Username":"X","Email":"X","Info":"X"}
{"Username":"X","Email":"X","Info":"X"}
But what I want is something like this:
[
{
"Username":"X",
"Email":"X",
"Info":"X"
},
{
"Username":"X",
"Email":"X",
"Info":"X"
}
]
How can I do this?
Thanks.
You have to build everything in an array and echo the json only after foreach finish. Like this:
$return = [];
foreach($result as $r){
$returnEcho["Id"] = $r["id"];
$returnEcho["Username"] = $r["username"];
$returnEcho["Email"] = $r["email"];
$returnEcho["Info"] = $r["Info"];
$return[] = $returnEcho;
}
echo json_encode($return);

How to covert php data into json format?

Here i am fetching data using php code.But i want the same code to be convert into json format.I am not getting the way to do it.
I have tried it in this way.
my code
while ($rows = mysql_fetch_array($filter)) {
$result['name'] = $rows['name'];
$result['id'] = $rows['id'];
}
$res = json_encode($result);
print_r($res);
getting result
{"name":["sradha","nicky","demo","testing"],"id":["1","2","3","4"]}
Here i want it in this below json format
[{id:1, name:'sradha'},
{id:2, name:'nicky'},
{id:3, name:'demo'},
{id:3, name:'testing'}];
Please suggest me.
Any suggestion will highly appreciate.
Thank you in advance.
Try below:
while ($rows = mysql_fetch_assoc($filter)) {
$result['name'] = $rows['name'];
$result['id'] = $rows['id'];
$new_result[] = $result;
}
$res = json_encode($new_result);
print_r($res);
OR
while ($rows = mysql_fetch_assoc($filter)) {
$result[] = $rows;
}
$res = json_encode($result);
print_r($res);
Try this
$result = array();
while ($rows = mysql_fetch_assoc($filter)) {
$result[] = $rows;
}
echo json_encode($result);
Create your array like this
$i=0;
while($rows = mysql_fetch_array($filter)) {
$result[$i]['name'] = $rows['name'];
$result[$i]['id'] = $rows['id'];
$i++;
}
$res = json_encode($result);
print_r($res);
It will return output result

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);

How to store values from foreach loop into an array?

Need to store values from foreach loop into an array, need help doing that.
The code below does not work, only stores the last value, tried $items .= ..., but that is not doing the trick either, any help will be appreciated.
foreach($group_membership as $i => $username) {
$items = array($username);
}
print_r($items);
Declare the $items array outside the loop and use $items[] to add items to the array:
$items = array();
foreach($group_membership as $username) {
$items[] = $username;
}
print_r($items);
Use
$items[] = $username;
Try
$items = array_values ( $group_membership );
<?php
$items = array();
$count = 0;
foreach($group_membership as $i => $username) {
$items[$count++] = $username;
}
print_r($items);
?>
You can try to do my answer,
you wrote this:
<?php
foreach($group_membership as $i => $username) {
$items = array($username);
}
print_r($items);
?>
And in your case I would do this:
<?php
$items = array();
foreach ($group_membership as $username) { // If you need the pointer (but I don't think) you have to add '$i => ' before $username
$items[] = $username;
} ?>
As you show in your question it seems that you need an array of usernames that are in a particular group :) In this case I prefer a good sql query with a simple while loop ;)
<?php
$query = "SELECT `username` FROM group_membership AS gm LEFT JOIN users AS u ON gm.`idUser` = u.`idUser`";
$result = mysql_query($query);
while ($record = mysql_fetch_array($result)) { \
$items[] = $username;
}
?>
while is faster, but the last example is only a result of an observation. :)
This is how you do it:
foreach($orders as $item){
$transactionIds[] = $item->generated_order_id;
}
dump($transactionIds);
This is assuming $orders collection has a field called 'generated_order_id'.
$items=array();
$j=0;
foreach($group_membership as $i => $username){
$items[$j++]=$username;
}
Just try the above in your code .
Just to save you too much typos:
foreach($group_membership as $username){
$username->items = array(additional array to add);
}
print_r($group_membership);
this question seem quite old but incase you come pass it, you can use the PHP inbuilt function array_push() to push data in an array using the example below.
<?php
$item = array();
foreach($group_membership as $i => $username) {
array_push($item, $username);
}
print_r($items);
?>

Categories