How to place one array inside another? - php

I've researched how to add an array inside another array but the result wasn't quite what I expected. I tried using 'array_push' and 'array_merge' but neither one solved my problem. Here's the code I have so far:
else if ($_GET['type'] == "listaJogos") {
//echo 'Tipo de operação: ' . $_GET['type'] . '<br>';
$campeonato_id = $_GET['campeonato'];
//Query que retorna a NOME_TIME, ID, DATA_HORA, TB_COTACAO_ID
$query = "SELECT GROUP_CONCAT(timee.nome_time ORDER BY timee.nome_time SEPARATOR ' X ') AS nome_time,
partida.id, partida.data_hora, partida.tb_cotacao_id
FROM tb_partida AS partida, tb_time AS timee, tb_partida_time AS partidaTime
WHERE (partida.id = tb_partida_id && timee.id = tb_time_id)
AND (partida.flag_ativo = 1 AND partida.flag_cancelado <> 1 AND partida.flag_finalizado <> 1)
AND partida.tb_campeonato_id = $campeonato_id
GROUP BY partida.id";
$query2 = "SELECT * FROM `tb_cotacao` WHERE `id` = ";
$result = mysqli_query($link, $query);
//--------------------------------------------------------------------------
while ($reg = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$registros[] = array('partida' => $reg);
$result2 = mysqli_query($link, $query2 . $reg['tb_cotacao_id']);
//$registros[] = array('partida' => mysqli_fetch_array($result2, MYSQLI_ASSOC));
array_push($registros, mysqli_fetch_array($result2, MYSQLI_ASSOC));
}
$saida = json_encode(array('json' => $registros));
echo $saida;
}
The code above gives me the output below:
"json": [
{
"partida": {
"nome_time": "Acreano\r X Flamengo\r",
"id": "4",
"data_hora": "2016-09-03 14:00:00",
"tb_cotacao_id": "4"
}
},
{
"id": "4",
"casa": "1.23",
"empate": "2.13",
"fora": "1.23",
"gol_meio": "6.00",
"mais_2gm": "7.00",
"menos_3gm": "7.67",
"ambas_marcam": "0.00",
"casa_empate": "6.00",
"fora_empate": "7.67",
"casa_marca": "6.00",
"fora_marca": "76.00",
"casa_ou_fora": "76.00",
"casavence_foramarca": "76.00",
"foravence_casamarca": "7.00",
"casavence_zero": "67.00",
"foravence_zero": "67.00"
}]
What I need is the array I'm trying to push to be inside 'partida', like this:
"json": [
{
"partida": {
"nome_time": "Acreano\r X Flamengo\r",
"id": "4",
"data_hora": "2016-09-03 14:00:00",
"tb_cotacao_id": "4"
"cotacoes": {
"id": "4",
"casa": "1.23",
"empate": "2.13",
"fora": "1.23",
"gol_meio": "6.00",
"mais_2gm": "7.00",
"menos_3gm": "7.67",
"ambas_marcam": "0.00",
"casa_empate": "6.00",
"fora_empate": "7.67",
"casa_marca": "6.00",
"fora_marca": "76.00",
"casa_ou_fora": "76.00",
"casavence_foramarca": "76.00",
"foravence_casamarca": "7.00",
"casavence_zero": "67.00",
"foravence_zero": "67.00"
}
}
}]
I'd really appreciate if someone can give me a hand with this.

array_push($registros[0]['partida'], mysqli_fetch_array($result2, MYSQLI_ASSOC));
use this
modify your 3rd line from last

Related

Compare variable of two different array?

Here i want compare two array.
I have two tables one is CATEGORY and second is USER(in which selected multiple category is stored in this format , , , ).
but when the USER want to update their category at that time the earlier selected category should return checked 1 and which is not selected should return checked 0 and here is my code.
case 'cat':
$sql="SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res=mysqli_query($con,$sql);
$response1 = array();
while ($array = mysqli_fetch_array($qry_res))
{
foreach (explode(',', $array['category']) as $cat)
{
$response1[]=array('category' => $cat);
$response['Selected_category'] = $response1;
}
}
$qry="SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res=mysqli_query($con,$qry);
$jsonData = array();
while ($array = mysqli_fetch_assoc($qry_res))
{
$jsonData[] = $array;
$response['category'] = $jsonData;
}
echo json_encode($response);
//echo json_encode(array('data1' =>$response1));
//
mysqli_close($con);
break;
and here is my fetched array from the database.
{
"Selected_category": [
{
"category": "5"
},
{
"category": "6"
},
{
"category": "9"
}
],
"category": [
{
"cat_id": "1",
"category": "Drug",
"image_url": "1.jpg"
},
{
"cat_id": "2",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "3",
"category": "Bars",
"image_url": "2.jpg"
},
{
"cat_id": "4",
"category": "Hair Saloon",
"image_url": "2.jpg"
}
]
}
This is for handle this same structure as You provided.
<?php
$response = [];
$sql = "SELECT category from nesbaty_user where user_id='".$user_id."'";
$qry_res = mysqli_query($con, $sql);
$selectedCategories = mysqli_fetch_array($qry_res);
$selectedCategories = explode(',', $selectedCategories['category']);
$qry = "SELECT cat_id,category,image_url FROM nesbaty_category";
$qry_res = mysqli_query($con, $qry);
while ($categories = mysqli_fetch_assoc($qry_res)) {
$categories['checked'] = (int)\in_array($categories['cat_id'], $selectedCategories);
$response[] = $categories;
}
echo json_encode($response);
mysqli_close($con);
If any error writes a comment, I'll fix it.

Multidimensional array combines same key and value into already defined array element

I new to php, getting mysql results storing json but its not gettng coorect format what I want.
Pease check below code
$sql = "select * from en_providers where providerEmailAddress='" . $email . "' and providerPW='" . $password . "'";
$result = mysqli_query($con, $sql) or die("Error in Selecting " . mysqli_error($connection));
if (mysqli_num_rows($result) > 0) {
$resultArray = array();
while ($row = mysqli_fetch_assoc($result)) {
$providerID = $row['providerID'];
$resultArray['providers'] = $row;
$resultArray['providers']['providerIDActivities'] = unserialize($row['providerIDActivities']);
$resultArray['providers']['providerIDBodies'] = unserialize($row['providerIDBodies']);
$resultArray['providers']['providerIDOthers'] = unserialize($row['providerIDOthers']);
$sql1 = "select * from en_venues where providerID = $providerID ";
$result1 = mysqli_query($con, $sql1) or die("Error in Selecting " . mysqli_error($connection));
$i = $j = $l = $x = $m = 0;
while ($row1[] = mysqli_fetch_assoc($result1)) {
//$resultArray['venues'][]['venueIDFacilities'] = unserialize($row1[$j++]['venueIDFacilities']);
$venueID = $row1[$j++]['venueID'];
$k = 0;
$venueFacilities = unserialize($row1[$i++]['venueIDFacilities']);
$resultArray[$x++]['venues']['venueIDFacilities'] = $venueFacilities;
//$resultArray['venues'][$x++]['venueID'] = $venueID;
$resultArray['venues'] = $row1;
//echo json_encode($resultArray);
echo json_encode($resultArray);
}
}
Output is:
{
0: {
"venues": {
"venueIDFacilities": [
"1",
"2",
"3"
],
}
},
1: {
"venues": {
"venueIDFacilities": [
"4",
"7"
],
}
}
},
"providers": {
"providerIDActivities": [
"218",
"219"
],
"providerIDSports": "a:1:{i:0;i:82;}",
"providerIDBodies": [
"112"
],
},
venues": {
0: {
"venueID": "9",
"providerID": "2"
},
1: {
"venueID": "238",
"providerID": "2",
"venueActive": "yes"
}
}
But I need those VenueFailities to be in respective venues but result is getting outside. How can I append those values into venues?
I am trying for one day with different ways but it's not getting correct format.
Output I want:
"providers": {
"providerIDActivities": [
"218",
"219"
],
"providerIDSports": "a:1:{i:0;i:82;}",
"providerIDBodies": [
"112"
],
},
venues": {
0: {
"venueID": "9",
"providerID": "2",
"venueIDFacilities": [
"4",
"7"
]
},
1: {
"venueID": "238",
"providerID": "2",
venueIDFacilities": [
"4",
"7"
]
}
}
This line
$resultArray[$x++]['venues']['venueIDFacilities'] = $venueFacilities;
should be
$resultArray['venues'][$x++]['venueIDFacilities'] = $venueFacilities;

How to join two queries from two tables into one query in PHP code?

I'm starting out to learning php and I wrote 2 queries to fetch data from two tables.
Currently, these are my tables:
food_vendors
ID Name Description
-----------------------------
1 Vendor 1 testing
2 Vendor 2 testing
3 Vendor 3 testing
food_vendor_menu
ID VENDOR_ID FOOD_NAME
-----------------------------
1 1 Food 1
2 1 Food 2
3 2 Food 3
4 2 Food 4
5 3 Food 5
Each vendor_id in food_vendor_menu corresponds to the id in food_vendors. Therefore, Vendor 1 would have 2 food items, as well as Vendor 2, while Vendor 3 only has 1 food item.
Currently, I'm making 2 queries and looping through them like so:
$sql = "select * from food_vendors";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$jsonData = array();
$rowCount = $result->num_rows;
$index = 1;
while($row =mysqli_fetch_assoc($result))
{
$sqlnew = "select * from food_vendor_menu where vendor_id=" .$row['id']. "" ;
$resultnew = mysqli_query($connection, $sqlnew) or die("Error in Selecting " . mysqli_error($connection));
$jsonData = array();
$rowCountnew = $resultnew->num_rows;
$indexnew = 1;
$menuStrings = array();
if ($rowCountnew >0)
{
while($rownew =mysqli_fetch_assoc($resultnew))
{
$menuStrings[$indexnew] = array("id" => $rownew['id'], "food_name" => $rownew['food_name']);
++$indexnew;
}
}
echo '"item'.$index.'":';
echo json_encode(array("id" => intval($row['id']), "name" => $row['name'], "description" => $row['description'], "menu_items" =>$menuStrings));
if ($rowCount != $index)
{
echo ',';
}
++$index;
}
echo ' }';
This produces the following output:
{
"item1": {
"id": 1,
"name": "Vendor 1",
"description": "testing":,
"menu_items": {
"1": {
"id": "1",
"food_name": "Food 1"
},
"2": {
"id": "2",
"food_name": "Food 2"
}
}
},
"item2": {
"id": 2,
"name": "Vendor 2",
"description": "testing"
"menu_items": {
"1": {
"id": "3",
"food_name": "Food 3"
},
"2": {
"id": "4",
"food_name": "Food 4"
}
}
},
"item3": {
"id": 3,
"name": "Vendor",
"description": "testing",
"menu_items": {
"1": {
"id": "5",
"food_name": "Food 5",
}
}
}
}
However, I don't believe this is the best way, and I like to produce the same output using only one query, so upon research, I try to learn and replaced the above code with the following, joining the 2 tables together:
$sql = "select * from food_vendor_menu s join food_vendors t on t.id=vendor_id" ;
$q = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$jsonData = array();
while($row = mysqli_fetch_assoc($q))
{
if (isset( $row['vendor_id'] ) )
{
$index = 'item'.$row['vendor_id'].'';
$jsonData[$index] = $row;
unset( $jsonData[$index]['food_name'] );
$jsonData[$index]['menu_items'] = array();
$jsonData[$index]['menu_items'] = $row['food_name'];
}
}
echo json_encode($jsonData);
The result of the output:
{
"item1": {
"id": "1",
"vendor_id": "1",
"name": "Vendor 1",
"description": "testing",
"menu_items": "Food 1"
},
"item2": {
"id": "2",
"vendor_id": "2",
"name": "Vendor 2",
"description": "testing",
"menu_items": "Food 3"
},
"item3": {
"id": "3",
"vendor_id": "3",
"name": "Vendor 3",
"description": "testing",
"menu_items": "Food 5"
}
}
I know this is the better approach and more efficient, but as you can see from the output above, the menu_items array for Vendor 1 only has Food 1, but no Food 2. The same issue with the other 2 vendors. Also, I need to append the vendor_id to each menu item, not just food name.
I know where the issue is, I just don't know how to fix it, due to my limited knowledge of php at the moment.
Can someone assist?
UPDATE:
Following Joey's suggestion, I replaced:
$jsonData[$index] = $row
$jsonData[$index]['menu_items'] = array();
$jsonData[$index]['menu_items'] = $row['food_name'];
with:
if ( !isset( $jsonData[$index] ) )
{
$jsonData[$index] = $row;
$jsonData[$index]['menu_items'] = array();
}
array_push($jsonData[$index]['menu_items'], $row['food_name']);
I get the following output:
"item1": {
"id": "1",
"name": "Vendor 1",
"description": "testing",
"menu_items": ["Food 1", "Food 2"]
}
However, I need to make each Food 1, Food 2, an array itself because I need to associate other data to each food item, like id, food price, etc.
$sql = "select * from food_vendor_menu s join food_vendors t on t.id=vendor_id";
...
$jsonData[$index] = $row
...
$jsonData[$index]['menu_items'] = array();
$jsonData[$index]['menu_items'] = $row['food_name'];
Should something like:
$sql = "select s.id as food_id, s.food_name, s.vendor_id, t.name, t.description from food_vendor_menu s join food_vendors t on t.id=vendor_id";
...
if (!isset($jsonData[$index])) {
$jsonData[$index] = $row;
unset( $jsonData[$index]['food_id'], $jsonData[$index]['food_name'] );
$jsonData[$index]['menu_items'] = array();
}
array_push($jsonData[$index]['menu_items'],
array('id'=>$row['food_id'], 'food_name'=>$row['food_name']));
Query:
$sql = "
SELECT
t.*,
GROUP_CONCAT(CONCAT(s.id, '%%',s.food_name) SEPARATOR '||') as menu_items
FROM
food_vendor_menu s
JOIN
food_vendors t
ON
t.id=vendor_id
GROUP BY
s.vendor_id
";
Php processing
//create an array
$jsonData = array();
$count = 1;
while($row = mysqli_fetch_assoc($q))
{
//lets place the row...
$jsonData['item'.$count] = $row;
//lets edit the menu_items by exploding it....
$menu_items = explode('||', $row['menu_items']);
$jsonData['item'.$count]['menu_items'] = [];
foreach($menu_items as $food_count => $food)
{
list($menu_id, $food_name) = explode('%%', $food);
$menu_item = (object)['id'=>$menu_id, 'food_name'=>$food_name];
$jsonData['item'.$count]['menu_items'][($food_count+1)] = $menu_item;
}
$count++;
}
echo json_encode($jsonData); //output it as a JSON encoded data...
I think its better that the menu_items is represented in array form (enclosed in []) rather than objects (enclosed in {}).

How to combine multiple SQL queries into one to output as JSON in PHP code?

I currently have the following table set up:
StartTime EndTime Performer Event Day Location
-----------------------------------------------------
1:00pm 2:00pm Test Test 0 1
11:00pm 12:00am Test Test 0 0
2:00pm 2:30pm Test Test 1 0
11:00pm 12:00am Test Test 2 1
The JSON output looks something like this:
{
"day0": {
"item1": {
"StartTime": "1:00pm",
"EndTime": "2:00pm",
"Performer": "Test",
"Event": "Test",
"Location": 1
},
"item2": {
"StartTime": "11:00pm",
"EndTime": "12:00am",
"Performer": "Test",
"Event": "Test",
"Location": 0
}
},
"day1": {
"item1": {
"StartTime": "2:00pm",
"EndTime": "2:30pm",
"Performer": "Test",
"Event": "Test",
"Location": 0
}
},
"day2": {
"item1": {
"StartTime": "11:00pm",
"EndTime": "12:00am",
"Performer": "Test",
"Event": "Test",
"Location": 1
}
}
}
Since I'm still learning PHP, I wrote some sloppy code by making 3 queries to the database, each time selecting all data where the day was 1, 2, and 3.
Here's an example of code for fetching data for day=0, which is repeated for day=1 and day=2:
echo '{ "day0" : {';
$sql = "select * from table WHERE day = 0";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$jsonData = array();
$rowCount = $result->num_rows;
$index = 1;
while($row =mysqli_fetch_assoc($result))
{
echo '"item'.$index.'":';
echo json_encode(array("StartTime" => $row['StartTime'], "EndTime" => $row['EndTime'], "Performer" => $row['Performer'], "Event" => $row['Event'], "Location" => intval($row['Location'])));
if ($rowCount != $index)
{
echo ',';
}
++$index;
}
echo ' }';
// Repeated code for day=1
// Repeated code for day=2
echo ' }';
I feel as though this can be achieved with just one query, but being that I'm new, I'm not sure how to implement it.
I started to do something like this:
$sql = "select * from table";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$jsonData = array();
$numOfRows = $result->num_rows;
$count = 1;
while($row = mysqli_fetch_assoc($result))
{
$outerIndex = 'day'.$row['day'];
if ($row['day'] == '1')
{
// Do something, not sure
}
if ( !isset( $jsonData[$outerIndex] ) )
{
$innerIndex = 'item'.$count.'';
$jsonData[$outerIndex][$innerIndex] = $row;
}
++$count;
}
echo json_encode($jsonData);
However, I just got stuck, and not really sure how to approach it further.
SQL:
$sql = "SELECT * FROM table ORDER BY Day";
Further down on code:
$result_object = [];
$item = 1;
while ($row = $result->fetch_assoc()) {
if(isset($result_object['day'.$row['Day']]))
{
$result_object['day'.$row['Day']]['item'.$item] = $row;
$item++;
}
else
{
$result_object['day'.$row['Day']]['item1'] = $row;
$item = 2;
}
}
You can then output it with:
echo json_encode($result_object, JSON_PRETTY_PRINT); //JSON_PRETTTY_PRINT is not necessary...
You may disagree with me, but I don't think indexing items with item0, item1 and so on.... or day0, day1 ... is a GOOD idea. I personally prefer that the looping through the result would be:
while ($row = $result->fetch_assoc()) {
if(isset($result_object[$row['Day']]))
{
$result_object[$row['Day']]->items[] = $row;
}
else
{
$result_object[$row['Day']] = (object)['day'=>$row['Day'], 'items'=>[$row]];
}
}
In this case, the result would be an array of objects. ie:
[
{
"day": "0",
"items": [
{
"StartTime": "07:23:56",
"EndTime": "17:24:04",
"Performer": "Performer1",
"Event": "Event1",
"Day": "0",
"Location": "1"
},
{
"StartTime": "09:24:30",
"EndTime": "01:04:37",
"Performer": "Performer2",
"Event": "Event2",
"Day": "0",
"Location": "1"
}
]
},
{
"day": "1",
"items": [
{
"StartTime": "10:25:22",
"EndTime": "11:25:29",
"Performer": "Performer2",
"Event": "Event3",
"Day": "1",
"Location": "2"
}
]
},
{
"day": "2",
"items": [
{
"StartTime": "12:26:08",
"EndTime": "13:26:12",
"Performer": "Performer3",
"Event": "Event4",
"Day": "2",
"Location": "1"
}
]
}
]
The reason: you can easily iterate through each values(an array) in whatever language you're going to use.

Merge results of single JSON output with PHP

I have a JSON array as per below:
{
"aaData": [
{
"Date_time": "23",
"traffic": "22",
"direction": "sent"
},
{
"Date_time": "24",
"traffic": "55",
"direction": "sent"
},
{
"Date_time": "25",
"traffic": "60",
"direction": "sent"
},
{
"Date_time": "26",
"traffic": "43",
"direction": "sent"
},
{
"Date_time": "27",
"traffic": "50",
"direction": "sent"
},
{
"Date_time": "23",
"traffic": "50",
"direction": "received"
},
{
"Date_time": "24",
"traffic": "42",
"direction": "received"
},
{
"Date_time": "25",
"traffic": "52",
"direction": "received"
},
{
"Date_time": "26",
"traffic": "47",
"direction": "received"
},
{
"Date_time": "27",
"traffic": "36",
"direction": "received"
}
]
}
What I'd like to do with it is combine all the results with the same date into a single entry - so for date_time 23 I want it to appear like this
"Date_time": "23",
"traffic-sent": "22",
"traffic-received": "50"
I'd like to do this with PHP if possible? The data is coming from two separate mySQL queries, coming from to different mySQL databases. I've tried combining the output of the query to do what I need (tried Joins and Unions) but can't get past the separation of the results as per my first example.
The part of the SQL query creating the JSON looks like this:
while($row = mysqli_fetch_assoc($result)) {
$model[$i]['Date_time'] = $row['the_day'];
$model[$i]['traffic'] = $row['traffic'];
$model[$i]['direction'] = $row['TABLE_NAME'];
$i++;
}
And the SQL looks like this:
(SELECT
DAY(`Time`) AS the_day,
count(accounts.accName) AS traffic,
"sent" AS TABLE_NAME
FROM
bss.ss_sent LEFT JOIN bss.accounts ON ss_sent.Customer = accounts.accName
WHERE
YEARWEEK(`Time`) = YEARWEEK(CURRENT_DATE)
AND
Customer != " "
AND
accShortName = "QRR"
GROUP BY
the_day)
UNION
(SELECT
DAY(Date_time) AS the_day,
count(AS_Task) AS traffic,
"received" AS TABLE_NAME
FROM
im_stats.as_counter
WHERE
AS_Task = "QRR3 Incoming"
AND
YEARWEEK(Date_time) = YEARWEEK(CURRENT_DATE)
GROUP BY
the_day
Order by the_day)
IF anyone can advise of a way to combine the results I'd very much appreciate it.
UPDATE:
This is how I've entered Populus's code:
$i = 0;
while($row = mysqli_fetch_assoc($result)) {
$model[$i]['Date_time'] = $row['the_day'];
$model[$i]['traffic'] = $row['traffic'];
$model[$i]['direction'] = $row['TABLE_NAME'];
$i++;
}
$combined = array();
foreach ($model as $val) {
$date_time = $val['Date_time'];
if (!isset($combined[$date_time)) {
$combined[$date_time] = array(
'Date_time' => $date_time,
'traffic_sent' => 0,
'traffic_received' => 0,
);
}
if ('received' == $val['direction']) {
$combined[$date_time]['traffic_received'] += $val['traffic'];
} else {
$combined[$date_time]['traffic_sent'] += $val['traffic'];
}
}
header('Content-type: application/json');
print json_encode(array('aaData' => $combined), JSON_PRETTY_PRINT);
This could probably be done using SQL (which you haven't provided), but if you really want PHP:
$combined = array();
foreach ($model as $val) {
$date_time = $val['Date_time'];
if (!isset($combined[$date_time])) {
$combined[$date_time] = array(
'Date_time' => $date_time,
'traffic_sent' => 0,
'traffic_received' => 0,
);
}
if ('received' == $val['direction']) {
$combined[$date_time]['traffic_received'] += $val['traffic'];
} else {
$combined[$date_time]['traffic_sent'] += $val['traffic'];
}
}
Your desired array is now in $combined. If you don't want the keys, you can remove it:
$result = array_values($combined);
Try it this way:
while($row = mysqli_fetch_assoc($result)) {
if ($row['direction'] == 'sent')
$dt[$row['Date_time']]['traffic-sent'] += $row['traffic'];
elseif ($row['direction'] == 'recieved')
$dt[$row['Date_time']]['traffic-recieved'] += $row['traffic'];
}
foreach ($dt as $date) {
echo "Date_time: " . key($date) . ",<br/>" .
"traffic_sent: " . $date['traffic-sent'] . ",<br/>" .
"traffic-recieved: " . $date['traffic-recieved'] . "<br/><br/>";
}

Categories