Encode multidimensional array using while loop - php

I have a multidimensional array and I want it printed like these by using PHP, but there is no comma separating the curly braces }{ and it should be like },{. Can you guys help me?
{"user_activity": [{
"log_number": "1",
"log_user_1": "w120511891",
"log_activity_id": "A0002DOC",
"log_user_2": "",
"log_document_id": "DSX00012",
"log_material_id": "",
"log_timestamp": "2021-10-23 13:52:35",
"log_rand_key": "127",
"log_hash_key": "09c7e3bb5d6f74c257aa4b4cdae388a69177c7dc",
"log_project_id": "1520002",
"log_number_reference": "",
"log_close": "1"
}{
"log_number": "9",
"log_user_1": "W201005911",
"log_activity_id": "A0004DOC",
"log_user_2": "",
"log_document_id": "DSX00012",
"log_material_id": "",
"log_timestamp": "2021-10-25 10:35:29",
"log_rand_key": "127",
"log_hash_key": "d04e8d1ef5c9f8b85a3f7556b92d6a7fcdc11639",
"log_project_id": "1520002",
"log_number_reference": "1",
"log_close": "1"
}]}
This is my PHP Code
echo "{\"user_activity\": [";
while($rsel_userAct_p = mysqli_fetch_array($xsel_userAct_p, MYSQLI_ASSOC)) {
print_r(json_encode($rsel_userAct_p), JSON_PRETTY_PRINT);
}
echo "]}";

You're doing it wrong. Just create an array, append data from MySQL into it and json_encode the array itself:
$array = [];
while ($rsel_userAct_p = mysqli_fetch_array($xsel_userAct_p, MYSQLI_ASSOC)) {
$array["user_activity"][] = $rsel_userAct_p;
}
echo json_encode($array, JSON_PRETTY_PRINT);
Or even better:
$array = [
"user_activity" => mysqli_fetch_all($xsel_userAct_p, MYSQLI_ASSOC)
];
echo json_encode($array, JSON_PRETTY_PRINT);

Your issue is that you are using print_r in the first place. print_r is meant to print out a very specific format which helps with array structures but has nothing to do with json.
Taken from the print_r documentation
<pre>
<?php
$a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z'));
print_r ($a);
?>
</pre>
will result in
Array
(
[a] => apple
[b] => banana
[c] => Array
(
[0] => x
1 => y
[2] => z
)
)
What you actually want (at least guessing from your code example) is you want to print out a single json object that consists of multiple results from your database, based upon the array result you got before.
So instead of using your current code, you create a proper array structure in the first place and then you print it out with the given json function.
$activities = [
'user_activity' => []
];
while($rsel_userAct_p = mysqli_fetch_array($xsel_userAct_p, MYSQLI_ASSOC)) {
$activities['user_activity'][] = $rsel_userAct_p;
}
echo json_encode($activities, JSON_PRETTY_PRINT);
The actual result should look exactly like you intend the result to be, and even works regardless of the amount of entries in your database.

This will make your JSON in correct format:
$json='{"user_activity": [{
"log_number": "1",
"log_user_1": "w120511891",
"log_activity_id": "A0002DOC",
"log_user_2": "",
"log_document_id": "DSX00012",
"log_material_id": "",
"log_timestamp": "2021-10-23 13:52:35",
"log_rand_key": "127",
"log_hash_key": "09c7e3bb5d6f74c257aa4b4cdae388a69177c7dc",
"log_project_id": "1520002",
"log_number_reference": "",
"log_close": "1"
}{
"log_number": "9",
"log_user_1": "W201005911",
"log_activity_id": "A0004DOC",
"log_user_2": "",
"log_document_id": "DSX00012",
"log_material_id": "",
"log_timestamp": "2021-10-25 10:35:29",
"log_rand_key": "127",
"log_hash_key": "d04e8d1ef5c9f8b85a3f7556b92d6a7fcdc11639",
"log_project_id": "1520002",
"log_number_reference": "1",
"log_close": "1"
}]}';
$json=str_replace("}{","},{",$json);
Then you can use :
echo "<pre>";
print_R(json_decode($json,true));
to convert JSON to PHP array.
You can use in while like:
$json = [];
while ($rsel_userAct_p = mysqli_fetch_array($xsel_userAct_p, MYSQLI_ASSOC)) {
$json["user_activity"][] = $rsel_userAct_p;
}
echo json_encode($json, JSON_PRETTY_PRINT);

Related

I'm trying to decode json array to php but it's returning a blank page

I'm trying to decode json array to php array using json_decode, but it's displaying a blank page
Here's the json array
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
Here's the code to decode json
$json = file_get_contents('http://localhost/example/index.php/destinations/json');
$data = json_decode($json,true);
$names = $data['result'];
echo "<pre>";
echo $names;
print_r($names);
Thanks
For obtaining proper JSON using json_decode() and json_encode() follow these guidelines:
json_decode() :
This function only works with UTF-8 encoded strings.
Returns the value encoded in json in appropriate PHP type. Values true, false and null are returned as TRUE, FALSE and NULL respectively. NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
The key and value must be enclosed in double quotes single quotes are not valid.
Your JSON:
[["id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"],["id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"]]
apears to be invalid. Arrays use [] while objects use {}.
This is an example of how a proper PHP array structure would look like prior to doing json_encode() (before sending):
// array structure in PHP to get proper JSON
Array ( [0] => Array ( [id] => 2 [name] => Sam Nju [photo] => 1510074080885.jpg [qty] => 10 [price] => 10000.00 ) [1] => Array ( [id] => 3 [name] => Daniel [photo] => 1510074047056.jpg [qty] => 0 [price] => 40000.00 ) )
which was obtained using the following:
json_decode('[{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}]', true)
which would mean doing this:
$myArray = array();
$firstPerson = array();
$secondPerson = array();
$firstPerson['id'] = 2;
$firstPerson['name'] = "Sam Nju";
// ...
$secondPerson['id'] = 3;
$firstPerson['name'] = "Daniel";
// ...
array_push($myArray, $firstPerson);
array_push($myArray, $secondPerson);
// or $myArray[0] = $firstPerson; and $myArray[1] = $secondPerson;
While valid JSON would look like this:
{{"id":"2","name":"Sam Nju","photo":"1510074080885.jpg","qty":"10","price":"10000.00"},{"id":"3","name":"Daniel","photo":"1510074047056.jpg","qty":"0","price":"40000.00"}}
If you are getting the data from a database you might want to use something like this:
$result = mysqli_query($con, "SELECT .... // database query, $con is connection variable
$myArray = array();
while($row = mysqli_fetch_array($result))
{
$tempArray = array();
$tempArray['id'] = $row[0];
$tempArray['name'] = $row[1];
$tempArray['photo'] = $row[2];
// ...
array_push($myArray, $tempArray);
}
// use print_r($myArray); to test it out.
Although your code looks correct, your JSON data is invalid. Objects are enclosed by {}, not []. Replace the JSON with this, and it should work.
[
{
"id": "2",
"name": "Sam Nju",
"photo": "1510074080885.jpg",
"qty": "10",
"price": "10000.00"
},
{
"id": "3",
"name": "Daniel",
"photo": "1510074047056.jpg",
"qty": "0",
"price": "40000.00"
}
]
Also above answer already mentioned it:
Your JSON is invalid. You can check this e.g. with an JSON linter like https://jsonlint.com/
Plus, you're referencing names with $names = $data['result'];. However, in your provided JSON there is no array (or better object), with key "result".
You may look up your PHP's error log file to understand where the problem lies.

PHP & JSON Decoding

I'm trying to decode some basic JSON data from Mintpal.com (https://www.mintpal.com/api)
The raw data looks like:
[
{
"market_id": "152",
"coin": "VeriCoin",
"code": "VRC",
"exchange": "BTC",
"last_price": "0.00008512",
"yesterday_price": "0.00009300",
"change": "-8.47",
"24hhigh": "0.00009450",
"24hlow": "0.00008050",
"24hvol": "13.153",
"top_bid": "0.00008063",
"top_ask": "0.00008591"
}
]
I just want to pull bits off this information out and assign them to variables. I use the below code with another near identical JSON output and it works fine.
//GET MINTPAL JSON DATA
$url = "https://api.mintpal.com/v1/market/stats/VRC/BTC";
$contents = file_get_contents($url);
$json = json_decode($contents);
//GET 'LAST BID' INFO
$lastBid = $json->code;
The previous raw JSON that works with the above code looks exactly the same, except for not being encased in '[...]' as the Mintpal one is.
{
"success": true,
"message": "",
"result": [
{
"MarketName": "BTC-LTC",
"High": 0.01126000,
"Low": 0.01060000,
"Volume": 442.30927821,
"Last": 0.01061100,
"BaseVolume": 4.86528601,
"TimeStamp": "2014-08-27T13:49:03.497",
"Bid": 0.01051801,
"Ask": 0.01061100,
"OpenBuyOrders": 50,
"OpenSellOrders": 116,
"PrevDay": 0.01079000,
"Created": "2014-02-13T00:00:00"
}
]
}
Any ideas on why I can't read the information this time round?
If you either did a var_dump() or a print_r() of your $json variable you should see that it is now an array starting at element 0 containing all the unique json elements.
//GET MINTPAL JSON DATA
$url = "https://api.mintpal.com/v1/market/stats/VRC/BTC";
$contents = file_get_contents($url);
$json = json_decode($contents);
pR($json);
//GET 'LAST BID' INFO
$lastBid = $json->code;
function pR($data){
echo "<pre>";
print_r($data);
echo "</pre>";
}
That yielded:
Array
(
[0] => stdClass Object
(
[market_id] => 152
[coin] => VeriCoin
[code] => VRC
[exchange] => BTC
[last_price] => 0.00008512
[yesterday_price] => 0.00009300
[change] => -8.47
[24hhigh] => 0.00009300
[24hlow] => 0.00008050
[24hvol] => 12.968
[top_bid] => 0.00008065
[top_ask] => 0.00008585
)
)

Searching JSON PHP

I have JSON that looks like this (shortened for readability):
{
"heroes": [
{
"name": "antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
{
"name": "axe",
"id": 2,
"localized_name": "Axe"
},
{
"name": "bane",
"id": 3,
"localized_name": "Bane"
}
]
}
I have a PHP variable that is equal to one of the three ids. I need to search the JSON for the id and return the localized name. This is what I’m trying so far.
$heroid = $myplayer['hero_id'];
$heroes = file_get_contents("data/heroes.json");
$heroesarray = json_decode($heroes, true);
foreach ($heroesarray as $parsed_key => $parsed_value) {
if ($parsed_value['id'] == $heroid) {
$heroname = $parsed_value['localized_name'];
}
}
Easy. Just use json_decode(). Explanation follows the code at the bottom.
// First set the ID you want to look for.
$the_id_you_want = 2;
// Next set the $json.
$json = <<<EOT
{
"heroes": [
{
"name": "antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
{
"name": "axe",
"id": 2,
"localized_name": "Axe"
},
{
"name": "bane",
"id": 3,
"localized_name": "Bane"
}
]
}
EOT;
// Now decode the json & return it as an array with the `true` parameter.
$decoded = json_decode($json, true);
// Set to 'TRUE' for testing & seeing what is actually being decoded.
if (FALSE) {
echo '<pre>';
print_r($decoded);
echo '</pre>';
}
// Now roll through the decoded json via a foreach loop.
foreach ($decoded as $decoded_array_key => $decoded_array_value) {
// Since this json is an array in another array, we need anothe foreach loop.
foreach ($decoded_array_value as $decoded_key => $decoded_value) {
// Do a comparison between the `$decoded_value['id']` and $the_id_you_want
if ($decoded_value['id'] == $the_id_you_want) {
echo $decoded_value['localized_name'];
}
}
}
Okay, the reason my first try at this did not work—and neither did yours—is your JSON structure was nested one more level deep that what is expected. See the debugging code I have in place with print_r($decoded);? This is the output when decoded as an array:
Array
(
[heroes] => Array
(
[0] => Array
(
[name] => antimage
[id] => 1
[localized_name] => Anti-Mage
)
[1] => Array
(
[name] => axe
[id] => 2
[localized_name] => Axe
)
[2] => Array
(
[name] => bane
[id] => 3
[localized_name] => Bane
)
)
)
First you have an array to begin with which could equate to $decoded[0] and then below that you have another array that equates to $decoded[0]['heroes'] and then in there is the array that contains the values which is structured as $decoded[0]['heroes'][0], $decoded[0]['heroes'][1], $decoded[0]['heroes'][2].
But the key to solving this was the print_r($decoded); which helped me see the larger structure of your JSON.
json_decode() takes a JSON string and (if the second parameter is true) turns it into an associate array. We then loop through this data with a foreach until we find the hero you want.
$json = ''; // JSON string
$data = json_decode($json, true);
foreach($data['heroes'] as $hero) {
if($hero['id'] === 2) {
var_dump($hero['localized_name']);
// Axe
// This will stop the loop, if you want to keep going remove this line
break;
}
}

I want to convert sting ( associative array sting ) into associative array?

i want to store associative array into a variable a as a string, and then convert the variable into array.
$var='"electirc_bill"=>array(
"type" => "number",
"required"=>"yes"
),
"electirc_bill_per"=>array(
"type" => "number",
"required"=>"yes"
),
"gass_bill"=>array(
"type" => "number",
"required"=>"yes"
)
)';
var_dump($var);
Use serialize and unserialize.
Convert the array to string:
$string = serialize($array);
Convert it back to an array:
$array = unserialize($string);
Edit: Based on your comment you seem to already have the array stored as a string and want to be able to convert it to an array. For that I would use eval but be cautious when using it with any user input as it could lead to security vulnerabilities within your code.
I've made a small example using your code here: http://codepad.org/rPNXPBlW
$var = '$array_var = array("One" => array("1.1", "1.2"), "Two" => array("2.1", "‌​2.2"));';
eval($var);
echo $array_var['One'][0]; // Shows 1.1
Use like below,
$json_str = json_encode($var);
first then use json_decode($json_str); where required
// save
file_put_contents('file.json', json_encode($array));
// load
$array = json_decode(file_get_contents('file.json'), true);
You can use serialize and unserialize like this:
<?
$var=array("electirc_bill"=>array(
"type" => "number",
"required"=>"yes"
),
"electirc_bill_per"=>array(
"type" => "number",
"required"=>"yes"
),
"gass_bill"=>array(
"type" => "number",
"required"=>"yes"
)
);
var_dump($var);
$string = serialize($var);
var_dump($string);
$array = unserialize($string);
var_dump($array );
?>
WORKING CODE
Here i give suggestion to use this array will meet your requirement
$name=array('parent1'=>array('childone'=>'harish','childtwo'=>'vignesh'),'parent2'=>array('childone'=>'our children'));
echo "<pre>";
print_r($name);
foreach($name as $parents)
{
foreach($parents as $child)
{
echo "<pre>"; print_r($child);
}
}

PHP: setting a number as key in associative array

I'm trying to recreate json from a DB, for the client side. Unfortunately some of the keys in the json are numbers, which work fine in javascript, however as a result PHP keeps treating them as numeric instead of associative arrays. each key is for a document. let me show you:
PHP:
$jsonobj;
while ($row = mysql_fetch_assoc($ms)) {
$key = strval($row["localcardid"]);
$jsonobj[$key] = json_decode($row["json"]);
}
// $jsonobj ist still a numeric array
echo json_encode($jsonobj);
the resulting json should look like this:
{
"0": {
"terd": "10",
"id": 0,
"text": "",
"pos": 1,
"type": 0,
"divs": [
{},
{}
],
"front": 1
}
"1": {
"terd": "10",
"id": 0,
"text": "",
"pos": 1,
"type": 0,
"divs": [
{},
{}
],
"front": 1
}
}
One obvious solution would be to save the whole json without splitting in up. however that doesnt seem wise in regards to the db. i wanna be able to access each document seperately. using
$jsonobj = array ($key => json_decode($row["json"]));
obviously works, but unfortunately just for one key...
EDIT: for clarification*
in php: there's a difference between
array("a", "b", "c")
and
array ("1" => "a", "2" => "b", "3" => "c").
the latter, when done like this $array["1"] = "a" results in array("a") instead of array("1" => "a")
ANSWERED HERE
Try
echo json_encode((object)$jsonobj);
I believe if you pass the JSON_FORCE_OBJECT option, it should output the object with numeric indexes like you want:
$obj = json_encode($jsonObj, JSON_FORCE_OBJECT);
Example:
$array = array();
$array[0] = array('test' => 'yes', 'div' => 'first', 'span' => 'no');
$array[1] = array('test' => 'no', 'div' => 'second', 'span' => 'no');
$array[2] = array('test' => 'maybe', 'div' => 'third', 'span' => 'yes');
$obj = json_encode($array, JSON_FORCE_OBJECT);
echo $obj;
Output:
{
"0": {
"test": "yes",
"div": "first",
"span": "no"
},
"1": {
"test": "no",
"div": "second",
"span": "no"
},
"2": {
"test": "maybe",
"div": "third",
"span": "yes"
}
}
Simply save both inside a single entry in the database: the separate field values AND the whole json structure inside a separate column. This way you can search by single fields and still get the valid json structure for easy handling.
For setting a number as key in associative array we can use following code
$arr=array(); //declare array variable
$arr[121]='Item1';//assign Value
$arr[457]='Item2';
.
.
.
print_r($arr);//print value

Categories