How to combine two or more mysql array in one - php

I have two table that has multiple rows. I want to combine those two tables rows into one long array which will be identified as one array
I wrote this code
$posts_sql = $db->query("SELECT * FROM posts WHERE id < $lastpost AND position = submitter order by id DESC LIMIT 5");
$posts_all = $db->fetch_all($posts_sql);
foreach($posts_all as $key => $posts_row){
$users_sql = $db->query("SELECT username,firstname,lastname,avatar FROM users WHERE username = '".$posts_row['submitter']."'");
$users_all = $db->fetch_assoc($users_sql);
$data[] = $posts_row;
$data[] = $users_all;
}
echo json_encode($data);
It makes duplicate arrays doesn't right...
That's how my result show
[{
"id":"39",
"hash":"070fcc8e73ba5f549f87",
"post":"hello\n",
"files":"",
"location":",
"GB","status":"1",
"position":"dabblos",
"submitter":"dabblos",
"source":"text",
"ip":"37.130.227.133",
"stamp":"1390197699"
},
{
"username":"dabblos",
"firstname":"dabb",
"lastname":"los",
"avatar":"no_avatar.png"
}]
please help me make it just one long array
I would like to see the output looks like this
{
"id":"39",
"hash":"070fcc8e73ba5f549f87",
"post":"hello\n",
"files":"",
"location":",
"GB","status":"1",
"position":"dabblos",
"submitter":"dabblos",
"source":"text",
"ip":"37.130.227.133",
"stamp":"1390197699"
"username":"dabblos",
"firstname":"dabb",
"lastname":"los",
"avatar":"no_avatar.png"
}

look at this,i have taken example values, it is working fine as you wanted
$arr=array(array("abc"=>"1","def"=>"2"),array("abcc"=>"11","deff"=>"22"));
echo json_encode($arr);
$final = array();
foreach($arr as $item) {
$final = array_merge($final, $item);
}
print_r($final);
output
[{"abc":"1","def":"2"},{"abcc":"11","deff":"22"}]//json_array
Array ( [abc] => 1 [def] => 2 [abcc] => 11 [deff] => 22 )//final array
UPDATE
json_encode the final array and you'll get the desired result
echo json_encode($final);
output
{"abc":"1","def":"2","abcc":"11","deff":"22"}

Untested:
$posts_sql = $db->query("SELECT * FROM posts WHERE id < $lastpost AND position = submitter order by id DESC LIMIT 5");
$posts_all = $db->fetch_all($posts_sql);
foreach($posts_all as $key => $posts_row) {
$users_sql = $db->query("SELECT username,firstname,lastname,avatar FROM users WHERE username = '".$posts_row['submitter']."'");
$users_all = $db->fetch_assoc($users_sql);
$data[] = $posts_row;
foreach($users_all as $user)
$data[] = $user;
}
}
echo json_encode($data);
// when you use json_decode use the 'true' flag as in
// $decodedJson = json_decode($json, true);

Merge them before you json_encode them:
$data[] = $posts_row;
$data2[] = $users_all;
$result = array_merge($data,$data2);
echo json_encode($result);

Related

json_encode result from sql database

Database:
id
strDomain
1
x.com
2
y.com
3
z.com
$domainSettings = array();
$db_domainList = DB::get("SELECT strDomain FROM domains ORDER BY id ASC;");
foreach($db_domainList as $row) {
$domainSettings = array($row->strDomain);
}
$result = array('allowedDomains' => $domainSettings);
echo json_encode($result, JSON_FORCE_OBJECT);
Current output: {"allowedDomains":{"0":"x.com"}}
I need output similar to this: {"allowedDomains":"x.com","y.com","z.com"}
Output of echo json_encode($db_domainList);:
[{"strDomain":"x.com"},{"strDomain":"z.com"},{"strDomain":"y.com"}]
If I understand your question correctly considering the needed output is invalid, this code should do the trick.
$db_domainList = DB::get("SELECT strDomain FROM domains ORDER BY id ASC;");
$domainSettings = []; //Just incase $db_domainList is empty
foreach($db_domainList as $row) {
$domainSettings[] = $row->strDomain;
}
$result = array('allowedDomains' => $domainSettings);
echo json_encode($result);
Note that I have removed JSON_FORCE_OBJECT flag since you are asking for an output that contains and array.
The output of the above code should look like this which is very close to what you are looking for.
{
"allowedDomains": [
"x.com",
"y.com",
"z.com"
]
}
If I don't misunderstand you requirement, then you can do this way-
$db_domainList = DB::get("SELECT strDomain FROM domains ORDER BY id ASC;");
foreach($db_domainList as $row) {
$domainSettings[] = $row->strDomain;
}
$result = array('allowedDomains' => implode(',',$domainSettings));
echo json_encode($result, JSON_FORCE_OBJECT);

json_encode from MySQL - but change column names on output

I've never really used json_encode, but it's easy enough to do:
$result = $dblink->query("SELECT * FROM Contracts LIMIT 3");
$dbdata = array();
while ( $row = $result->fetch_assoc()) {
$dbdata[]=$row;
}
echo json_encode($dbdata);
/tada!
However, if I want to give the output data custom "column names", is there a simple way of doing this?
So, rather than outputting something like:
[{"TableColumn1":"147","TableColumn2":"9","TableColumn3":"39","TableColumn4":"32","TableColumn5":"41"...
I can have something like:
[{"My Own Title":"147","My Own Title 2":"9","My own title 3":"39",...
Try this
$result = $dblink->query("SELECT * FROM Contracts LIMIT 3");
$dbdata = array();
while ( $row = $result->fetch_assoc()) {
$rowarray = [];
$rowarray['My Own Title 1'] = $row['TableColumn1'];
$rowarray['My Own Title 2'] = $row['TableColumn2'];
$rowarray['My Own Title 3'] = $row['TableColumn3'];
$dbdata[]=$rowarray;
}
echo json_encode($dbdata);

Php array from sql result

How can i create an array from the result? I would like to use the array in a mysql IN() query.
//$array = array();
$get_subscategoria = mysqli_query($kapcs, "SELECT kat_id FROM termek_kategoria WHERE kat_parent = '$id'");
if(mysqli_num_rows($get_subscategoria) > 0 )
{
while($sub_kat = mysqli_fetch_array($get_subscategoria))
{
echo $sub_kat['kat_id'];
//$array[] = $sub_kat;
}
}
//print_r( $array );
Now, this code gives back 4 row ID, that works okay. I would like an array with these ID-s, like 1,2,3,4.
Instead of:
while($sub_kat = mysqli_fetch_array($get_subscategoria))
{
echo $sub_kat['kat_id'];
//$array[] = $sub_kat;
}
use:
$array = mysqli_fetch_assoc($get_subscategoria);
while($sub_kat = mysqli_fetch_array($get_subscategoria))
{
$array[] = $sub_kat['kat_id'];
}
echo implode(",",$array);
it give a result like 1,2,3,4
For MySQL, also you can use group_concat, only gives you one record:
SELECT GROUP_CONCAT(kat_id) AS kat_id
FROM termek_kategoria
WHERE kat_parent = '$id'
GROUP BY kat_parent

How to fetch all the matched rows from a Mysql table in a PHP array

I am trying to get the matched rows from a table and save it in a Global Array so that I can use it in different functions.
But when I do print_r of that array it shows only last row.
Here is my code
function setCampoFeed()
{
echo $sql = "SELECT campofeed.tag,campofeed.registro,campofeed.valor FROM campofeed ".
"INNER JOIN registrofeed ON registrofeed.id = campofeed.registro ".
"WHERE registrofeed.feed='".$this->idFeed."'";
$result= $this->localDb->execute($sql);
$this->campoFeed= mysql_fetch_array($result))
}
So here campoFeed is the array that should have all the rows of the match, but now its just having the last row.
Thanks in advance
Use
$this->campoFeed[] = mysql_fetch_array($result);"
insted of
$this->campoFeed= mysql_fetch_array($result);
You will get all data in array
Try this one if it works for you..
$resultArray = array();
$campoFeed = array();
$resultArray = mysql_fetch_array($result);
foreach($resultArray as $key => $value){
$campoFeed[$key] = $value;
}
print_r($campoFeed);
Use this
$mergedArray=array();
while($data= mysql_fetch_array($result)) {
$final_array = unserialize($data['data']);
$mergedArray=array_merge($mergedArray,$final_array);
}
array_unique($mergedArray, SORT_REGULAR);

Fetching An Array With MySQL / PHP

I have an existing database which has a table called PERSON with a field called NAME. What I’m trying to do is select all of the rows in the table where the NAME is "bill". And then I want the result to be stored in an array that I can step through at a later point.
Now, the problem is my code will only select the FIRST row with the name "bill" and ignore the rest of the rows where the NAME is "bill". At least that’s how it appears when I print out the array contents with print_r(). My code below:
<?php
$getAllPreview = "SELECT * from PERSON where NAME = 'bill'";
$getAllResult = #mysql_query( $getAllPreview );
$getAllRows = #mysql_fetch_assoc( $getAllResult );
print "<pre>";
print_r($getAllRows);
print "</pre>";
?>
<?php
$getAllPreview = "SELECT * from PERSON where NAME = 'bill'";
$getAllResult = #mysql_query( $getAllPreview );
while ($row = #mysql_fetch_assoc( $getAllResult ) ) {
$getAllRows[] = $row;
}
print "<pre>";
print_r($getAllRows);
print "</pre>";
?>
while($row = mysql_fetch_array($getAllResult, MYSQL_ASSOC)) {
$data[] = $row;
}
You just keep looping over mysql_fetch_assoc until no further rows are returned. If you want to output or process them, just do so in each iteration of the loop, as it's more efficient than placing it in an array first. But here you go anyway:
$allRows = array ();
while ($row = mysql_fetch_assoc( $getAllResult)) $allRows [] = $row;
<?php
$getAllPreview = "SELECT * from PERSON where NAME = 'bill'";
$getAllResult = #mysql_query( $getAllPreview );
$num_rows = mysql_num_rows($getAllResult);
while ($row = #mysql_fetch_assoc($getAllResult))
{
for($i=0;$i<$num_rows;$i++)
{
$array[] = $row;
}
}
?>

Categories