Please, help me a bit, i tried in any possible way to acces a nested json data, but without succes.
json
string(701) "{"status":"SUCCESS","products":{"6605995":{"is_bundle":false,"ean":"5949234930002","sku":"KNK-BAN-MP","tax_rate":19,"weight":0,"height":0,"width":0,"length":0,"star":0,"category_id":647123,"manufacturer_id":174472,"text_fields":{"name":"Bandaje Box Knockout Balcescu"},"stock":{"bl_11206":79},"prices":{"10929":69},"locations":{"bl_11206":""},"links":{"shop_4000268":{"product_id":"6665093873699","variant_id":"0"}},"average_cost":0,"average_landed_cost":0,"images":{"1":"https:\/\/cdn.shopify.com\/s\/files\/1\/0273\/9034\/5251\/products\/image.jpg?v=1657567836","2":"https:\/\/cdn.shopify.com\/s\/files\/1\/0273\/9034\/5251\/products\/image_37af2a9f-83c9-4a1f-84d6-3ad0e6aa62a3.jpg?v=1657567836"}}}}"
SCRIPT details above, basically, i need to replacesome how [static product id] details in comments
$arr = [
'inventory_id' => $inventoryid,
'products' => []
];
$q = $dbc->query("SELECT bpID FROM Products LIMIT 3");
while($row = mysqli_fetch_assoc($q)) {
$bpID = $row['bpID'];
$arr['products'][] = $row['bpID'];
}
$getproductidsp = [
'method' => 'getInventoryProductsData',
'parameters' => json_encode($arr),
];
$ch = curl_init();
$output = curl_exec($ch);
$data = json_decode($output, true);
var_dump($data);
foreach($data['products'][$bpID]['links'] as $key => $val){
$prod = $val['product_id'];
$variant = $val['variant_id'];
$query = "UPDATE IGNORE Products SET spID='$prod', svID='$variant' WHERE bpID='$bpID';";
$result = mysqli_query ($dbc, $query) or die (mysqli_error($dbc));
echo $result;
mysqli_close($dbc);
from the provided data, it works
foreach($data['products'][6605995]['links'] as $key => $val){
print_r($val);
}
and result is
Array
(
[product_id] => 6665093873699
[variant_id] => 0
)
working demo -> here
in the foreach ['links'], the key is shop and the product_id and variant_id are the values
foreach($data['products'][6605995]['links'] as $key => $val){
$prod = $val['product_id'];
$variant = $val['variant_id'];
}
edit2: looping products
Related
I am trying to JSON decode row Options and encode it with rest of data. But it is only giving me Options row but. If I don't decode it give me this with backslashes in Options row.
[{"ID":"4","AppID":"1","Question":"test2","Type":"Radios","OrderNumber":"2","Options":"{\"Number1\":
\"Yes\", \"Number2\": \"No\"}"}]
//open connection to mysql db
$connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbdata) or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from App_Questions";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while ($row =mysqli_fetch_assoc($result)) {
if ($row["Options"]){
$str = json_decode($row["Options"]);
$emparray = $str;
}else{
$emparray[] = $row;
}
}
echo json_encode($emparray);
Assuming you want to decode the field "Options" which has json data saved to it, and then you want to encode those json data with rest of the other fields. The json decoded output is this from our question:
array (
0 =>
array (
'ID' => '4',
'AppID' => '1',
'Question' => 'test2',
'Type' => 'Radios',
'OrderNumber' => '2',
'Options' => '{"Number1": "Yes", "Number2": "No"}',
),
)
If you decode "Options", you get this:
array (
'Number1' => 'Yes',
'Number2' => 'No',
)
You can do something like this to encode this with rest of the data inside the loop:
$decodedData = json_decode($results);
foreach ($decodedData as $row) {
if (isset($row->Options)) {
$decodedOptions = json_decode($row->Options);
foreach ($decodedOptions as $key => $value) {
$row->$key = $value;
}
}
}
$decodedData = json_encode($decodedData);
print_r($decodedData);
I am fetching data from location MySql table as structure is below
in my PHP code
I need send Json output in response as below (Table data may not be same as below json data but the format is same)
http://jsoneditoronline.org/?id=7c5600712df6f9ec1f8fbb8a13aba3de
Tried to do the following in the code to convert the array that i fetch from the table but however am unable to get it in the right format
$sql = "SELECT * FROM mobile_user_regions";
$stmt = $this->db->prepare($sql);
$stmt->execute();
$resCArray = $stmt->fetchAll(PDO::FETCH_ASSOC);
$ress = array();
foreach ($resCArray as $key => $value) {
$ress['regions'][] = array(array(
'name' => $value['region'],
'location' => array(
array(
'name' => $value['location'],
'store' => array(
'store_details' => $value['store_details'],
'store_phone' => $value['store_phone'],
'store_email' => $value['store_email'],
'store_latitude' => $value['store_latitude'],
'store_longitude' => $value['store_longitude']
)
)
)
)
);
Output: that i am getting is
**http://jsoneditoronline.org/?id=4d4a75177350e254ceee7238af13f2f7**
$regionArray = $xyzObject->getRegion();
if (!empty($regionArray) && isset($regionArray)) {
$i = 0;
$locationData = array();
foreach ($regionArray as $key => $value) {
$locationData['regions'][$i]['name'] = $value['region'];
$locationArray = $xyzObject->getLocation($value['region']);
$locationData['regions'][$i]['locations'] = $locationArray;
$i++;
}
$j = 0;
foreach ($locationData['regions'] as $key => $regions) {
$k = 0;
foreach ($regions['locations'] as $key1 => $locations) {
$storeArray = $xyzObject->getStore($locations['name']);
$locationData['regions'][$j]['locations'][$k]['stores'] = $storeArray;
$k++;
}
$j++;
}
echo json_encode($locationData);
I am developing a webservice for and android app the webservice is in PHP fetching data from a MySQL database ... The problem that I am having is that some of the projects have multiple details but my code is only fetching one detail for every project. I am getting the data in JSON format.
You can check this Here
Here is my code
function requiredData(){
$db = $this->dbConnection();
//$sql = "SELECT * FROM projects JOIN project_details ON projects.project_id=project_details.project_id";
$sql = "SELECT * FROM projects";
$queryResult = $db->query($sql);
if($queryResult->num_rows > 0){
while($row = $queryResult->fetch_assoc()){
$pid = $row['project_id'];
$detailsql = "SELECT * FROM project_details WHERE project_id=$pid";
$sqlResult = $db->query($detailsql);
if($sqlResult->num_rows > 0){
while ($d = $sqlResult->fetch_assoc()){
$r = array(
"project_id" => $d['project_id'],
"project_detail" => array(
"work_done" => $d['project_detail'],
"payment_for_work" => $d['project_payment'],
"payment_status" => $d['project_payment_status'],
"detail_id" => $d['project_detail_id']
)
);
}
}
$results[$row['project_name']] = array(
"project_id" => $row["project_id"],
"project_start_date" => $row["project_start_date"],
"project_due_date" => $row["project_due_date"],
"project_currency" => $row["project_currency"],
"project_work_details" => $r
);
}
}
return $results;
}
Thanks in advance for your help
The issue is in the second while loop. You are assigning array to $r, and $r value overwrites every time.
So, I am assigning now array to an other array, So it will become 2 dimensional array, like this;
while ($d = $sqlResult->fetch_assoc()){
$r[] = array(
"project_id" => $d['project_id'],
"project_detail" => array(
"work_done" => $d['project_detail'],
"payment_for_work" => $d['project_payment'],
"payment_status" => $d['project_payment_status'],
"detail_id" => $d['project_detail_id']
)
);
}
Now you can use $r, it will have multiple details of the project.
I'm building an angular application, so I have a PHP script extracting the database data into a JSON when requested.
This is what I'm using to extract the data into an array:
$values = array();
$query = "SELECT * FROM photos ORDER BY id";
$result = $mysqli->query($query);
while ($row = $result->fetch_array(MYSQL_ASSOC)) {
array_push($values, $row);
}
json_encode($values);
But it gives no result.
After some testing, if I change json_encode($values); to print_r($values); it actually print the table array, here an extract:
Array (
[0] => Array (
[id] => 4
[title] => Feel the Moment
[views] => 6
)
It seems the script is not creating a valid array.
$query = "SELECT * FROM photos ORDER BY id";
if ($result = $this->mysqli->query($query)) {
$json = array();
while ($row = $result->fetch_assoc()) {
$json[] = $row;
}
echo json_encode($json);
}
Your while is not executing, probably because you don't have any returned values from database.
I tested this code and it works well:
$json = array();
$json[] = array(
"id" => 1,
"category" => 'a',
"tags" => 't');
$json[] = array(
"id" => 2,
"category" => 'b',
"tags" => 'tt');
echo json_encode($json);
The result is:
[{"id":1,"category":"a","tags":"t"},{"id":2,"category":"b","tags":"tt"}]
And you'd better use mysqli_fetch_row or mysqli_fetch_assoc.
Try to debug your code. You may use var_dump($result->fetch_assoc()) to see if the query has some results.
$result = mysql_query($query);
$leaderboard = array();
while($row = mysql_fetch_assoc($result)) {
$leaderboard[$row["username"]] = $row["score"];
}
$output = array
(
'status' => 1,
'content' =>$leaderboard
);
print_r(json_encode($output));
right now the $output array is such JSON:
{"tim":"120","john":"45","larry":"56"}
but I want to have them as key-value pair so instead I want to be like:
{"name":"tim","score":120","name":"john","score="45", etc.}
and if I need that way, how do I modify the $leaderboard array so the output would be like that?
$leaderboard[] = Array('name' => $row["username"], 'score' => $row["score"]);