How to read a JSON Array in php without any key? - javascript

I have a JSON formed #Javascript and passed to PHP via AJAX , problem is that I cannot assign keys to each JSON Object inside the JSON Array .
The JSON Array looks something like this :
[{"jobId":"90","cname":"Subhasish","removal_id":101,"quantity":"3"},{"jobId":"90","cname":"Subhasish","removal_id":102,"quantity":"2"},{"jobId":"90","cname":"Subhasish","removal_id":103,"quantity":"4"},{"jobId":"90","cname":"Subhasish","removal_id":104,"quantity":"4"},{"jobId":"90","cname":"Subhasish","removal_id":105,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":106,"quantity":"5"},{"jobId":"90","cname":"Subhasish","removal_id":107,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":108,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":109,"quantity":"4"}]
,Now , in PHP ,how to iterate the data , I am a newbie to PHP , so please excuse me if I am asking a very silly question.
The link you provided has examples with key, mine is without key.
Thanks

$json = '[{"jobId":"90","cname":"Subhasish","removal_id":101,"quantity":"3"},{"jobId":"90","cname":"Subhasish","removal_id":102,"quantity":"2"},{"jobId":"90","cname":"Subhasish","removal_id":103,"quantity":"4"},{"jobId":"90","cname":"Subhasish","removal_id":104,"quantity":"4"},{"jobId":"90","cname":"Subhasish","removal_id":105,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":106,"quantity":"5"},{"jobId":"90","cname":"Subhasish","removal_id":107,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":108,"quantity":0},{"jobId":"90","cname":"Subhasish","removal_id":109,"quantity":"4"}]';
$array = json_decode($json,true);
foreach($array as $item) {
echo $item['jobId']."-".$item['cname']."-".$item['removal_id']."-".$item['quantity']."\n";
}
Output
90-Subhasish-101-3
90-Subhasish-102-2
90-Subhasish-103-4
90-Subhasish-104-4
90-Subhasish-105-0
90-Subhasish-106-5
90-Subhasish-107-0
90-Subhasish-108-0
90-Subhasish-109-4
Example

Using json_decode($json_object).
$json = json_decode($json_object);
foreach($json as $j){
print_r($j)
}

Related

How to search Steam game API JSON output?

I am working with following APIs:
http://api.steampowered.com/ISteamApps/GetAppList/v0002/?format=json
https://store.steampowered.com/api/appdetails?appids=GAMEID
(gameid example: "730" - counter strike)
My goal with both of these is to search them for data. For example I want the first API to give me a name of a game based on it's ID and the second one to give me specific information about a game for example if it has trading cards (id:29 in the API).
I tried a few things but I am kinda lost on this beacuse I don't really understand JSON so I would really appreciate some help.
I am open to both PHP and JS solutions.
IN PHP, you can use the json_decode() function to convert JSON data into an array. You can them access the values as you do for a classic array :
$appID = 730 ;
$url = 'https://store.steampowered.com/api/appdetails?appids=' . $appID ;
$content = file_get_contents($url) ; // retrieve the JSON data string from the website
$data = json_decode($content, true); // convert the JSON string into PHP array
echo $data[$appID]['data']['name'] ; // Counter-Strike: Global Offensive
var_dump($data[$appID]['data']['is_free']); // bool(true)

Getting mysql data into a var array

Im using MySQL to obtain data into $username and $chance.
There are two usernames in the data but it only loads the first one.
var data = [
{
"name" : "<?php echo $username; ?>",
"hvalue" : <?php echo $chance; ?>
},
];
To give a correct answer, we'll have to know what your variables $username and $chance exactly look like.
If you only have a string there, then only one value is possible.
If these variables are php arrays, you'll have to use json_encode to make a JSON array from them, before you can add them to your javascript object. (see https://secure.php.net/manual/en/function.json-encode.php)
Anyway, the best way to send a PHP array to JS would be to create the whole array in PHP and then encode it to JSON in order to use all the values in JS.
var data = <?php echo json_encode($data); ?>
More advanced: use an ajax request to avoid mixing up PHP an JS. But that's another story.

Not getting return values in $getJSON object

Javascript:
$.getJSON("path", function(data){alert(data.name)})
Guys in this line "data" is not working as an object. name is unrecognizable here.
I am sending multiple outputs in php using json_encode() function but not able to get those values in javascript file.
PHP Code:
$book = array("name"=>"bob", "num"=>1);
echo json_encode($book);

Get a MySQL stored array in string format and convert to array in JSON object

I have an array stored in a mysql table, like this:
[3,5,6,7,8]
When I select it, encode it as JSON in PHP and then parse it into a javascript object, instead of it becoming an array, it just becomes a string "[3,5,6,7,8]". I know it's not possible to store it as an array in a single field, so.. what could I do so it will convert properly to an array instead of string?
My current code:
test = JSON.parse('[{"id":43,"incidence":"[0,3,6,7]"}]')
I could solve it removing the " on the string, but mysql returns it with the string, php encodes with the quotes and javascript parses with quotes. So basically, is there a way to remove it in this process?
The problem lies on how you are constructing your array prior turning it into JSON. Since you are retrieving these results from the database, I am assuming you are constructing a multidimensional array that may look something like this:
$results = array(
array(
"id" => 43,
"incidence" => "[0,3,6,7]"
)
);
Because incidence is a string, it is giving you those errors when using it in JS. To solve you need to turn that string into an array. Now, since you might have more than one result (being that these are database results) you need to iterate through the result array and turn that string into an array like this:
foreach ($results as &$row) { // <-- notice the & symbol (Passing by reference)
$no_brackets = trim($row["incidence"], '[]');//if you stored your array as comma delimited value, you would not need this.
$row["incidence"] = explode(',', $no_brackets);
}
Lastly, use json_encode and pass it to JS.
Final Result:
<?php
foreach ($results as &$row) {
$no_brackets = trim($row["incidence"], '[]');
$row["incidence"] = explode(',', $no_brackets);
}
$json = json_encode($results);
?>
<script>
var obj = JSON.parse('<?= $json ?>');
console.log(obj);
</script>
Hope this helps.
You need to do a little fiddling to get this to work.
Try this
<?php
$string = '[3,5,6,7,8]';
$t = str_replace(array('[',']'), '', $string);
$array = explode(',', $t);
echo json_encode($array);
The result is
["3","5","6","7","8"]

Populate PHP Array Values in Javascript

Here is my code:
I am getting data from mysql query and getting array of values. But i am not able to populate in javasript. could you please any one help me out...
PHP Code:
$parishFamilyInfo = $parishFamilyInfoBO->sendBirthdayGreeting($personalInfoSearchDO, $parishFamilyInfoSearchDO);
foreach ($parishFamilyInfo as $parishFamily){
if(!empty($parishFamily->email)){
print_r($parishFamily);
}
}
JavaScript:
$(document).ready(function(){
var t = $('#people').bootstrapTransfer(
{'target_id': 'multi-select-input',
'height': '15em',
'hilite_selection': true});
t.populate([ /*here i need to populate php array value*/
{
value:"<?php print_r($parishFamily->email);?>",
content:"<?php print_r($parishFamily->name);?>"
},
]);
//t.set_values(["2", "4"]);
//console.log(t.get_values());
});
print_r is only for debugging. It's not for anything else. Let me quote the documentation:
print_r — Prints human-readable information about a variable
As stated above, it is a debugging function that's used to print the contents of a variable in a more readable manner. It just returns a string — JavaScript does not and will not understand this format.
Use JSON (JavaScript Object Notation) instead. It is is a light-weight data interchange format that is very popular nowadays. You can use the built-in function json_encode to create the JSON representation of your PHP array and then transfer it to JavaScript. JSON being language independent and based on the JavaScript scripting language, your JavaScript code will now be able to parse the array:
t.populate([
{
value: <?php echo json_encode($parishFamily->email); ?>,
content: <?php echo json_encode($parishFamily->name); ?>
},
]);

Categories