Display JSON on profilepage - php

How to display the names of accounts on user's profile page? So there would be displayed holidays and savings next to Accounts:
I'm new to coding and I'm trying to display the names of accounts (not the id) that user has and it should be displayed on their profile page. The accounts are saved in clients.json file. Thanks for help!
data/clients.json
{
"data": {
"tomas": {
"name": "eter",
"accounts": {
"5c7072a835c3b": {
"balance": 1000,
"name": "savings"
},
"5c7072a835c36": {
"balance": 1000,
"name": "holidays"
}
}
}
}
}
my PHP file :
<?php
session_start();
if (!isset($_SESSION['sUserId'])) {
header('Location: login.php');
}
$sUserId = $_SESSION['sUserId'];
$sData = file_get_contents('data/clients.json');
$jData = json_decode($sData);
if ($jData == null) {
echo 'System update';
}
$sTotalBalance = array_sum(array_column((array)$jData->data->$sUserId->accounts, 'balance'));
require_once 'top.php';
?>
<div><h5>Username:</h5> <?php echo $sUserId; ?></div>
<div><h5>Name: </h5><?php echo $jData->data->$sUserId->name; ?></div>
<div><h5>Accounts: </h5><?php echo $jData->data->$sUserId->accounts; ?> kr </div>
<?php
$sLinkToScript = '<script src="js/profile.js"></script>';
require_once 'bottom.php';
?>

Try iterating it as follows -
foreach($jData->data->$sUserId->accounts as $acc) {
echo $acc->name;
}

Related

How to use array_key_exists in foreach loop for JSON

I have some code that iterates over JSON in my project to display reviews in a slider. This code works, however I only want to display reviews where the array key 'comment' exists. I feel like the solution must be using array_key_exists, but I can't get the code correct (I'm still quite a novice with PHP). I've tried searching all over SO without much success. Here's an example of some of the JSON I'm working with; REVIEW ID 1 is review that I want to display, and REVIEW ID 2 is one I want to skip:
{
"reviewId": "{REVIEW ID 1}",
"reviewer": {
"profilePhotoUrl": "{PROFILE PHOTO URL}",
"displayName": "PERSON 1"
},
"starRating": "FIVE",
"comment": "This is a review",
"createTime": "2019-08-30T15:38:59.412Z",
"updateTime": "2019-08-30T15:38:59.412Z",
"reviewReply": {
"comment": "{REVIEW REPLY}",
"updateTime": "2019-08-30T16:05:58.184Z"
},
"name": "accounts/{ACCOUNT NUMBER}/locations/{LOCATION NUMBER}/reviews/"
},
{
"reviewId": "{REVIEW ID 2}",
"reviewer": {
"profilePhotoUrl": "{PROFILE PHOTO URL}",
"displayName": "PERSON 2"
},
"starRating": "FIVE",
"createTime": "2019-02-07T14:59:28.729Z",
"updateTime": "2019-02-07T14:59:28.729Z",
"name": "accounts/{ACCOUNT NUMBER}/locations/{LOCATION NUMBER}/reviews/"
},
And here's the code that runs the reviews:
$jsonreviews = plugin_dir_path( __DIR__ ) . './latest.json';
$reviews2var = file_get_contents($jsonreviews);
$reviews = json_decode($reviews2var, true);
$starpath = plugin_dir_url( __FILE__ ) . './img/fivestars.svg';
$truckpath = plugin_dir_url( __FILE__ ) . './img/chad_love_truck.png';
// Start buffer
ob_start();
?>
<div class="reviews-background">
<div class="swiper-container review-container">
<div class="swiper-wrapper review-wrapper">
<?php
$counter = 1;
foreach ($reviews['reviews'] as $review) :
if ($counter > 3) {
//do nothing
} else {
?>
<div class="swiper-slide review-slide">
<img src="<?php echo $starpath;?>" alt="5 Stars" class="five-stars" />
<?php $counter++;?>
<div class="truncate" data-excerpt>
<div data-excerpt-content>
<p class="slider-review-text">
<?php echo $review['comment'];?></p>
</div>
</div>
<p class="slider-review-auth">
<?php echo $review['reviewer']['displayName'];?>,
</p>
</div>
<?php } ?>
<?php endforeach;?>
How can I properly implement array_key_exists in the above, or should I be doing something else entirely? Thank you
You can check if comment is NOT set here:
if ($counter > 3 || !isset($review['comment'])) {
//do nothing
} else {
$counter++;
//HTML
}
However, I would probably flip the if logic and you won't need an else:
if ($counter <= 3 && isset($review['comment'])) {
$counter++;
//HTML
}
If you have large arrays, you probably want to break out of the loop if you have displayed more than 3 (or some number):
if ($counter > 3)
break;
} elseif (isset($review['comment'])) {
$counter++;
//HTML
}
You can substitute !array_key_exists and array_key_exists for the issets if you want.
I think this is the simple approach
if(isset($test[$key_check])){
echo $value = $test[$key_check];
}
Or check for array exist :
if (array_key_exists($key_check, $test)) {
return $test[$key_check];
}

foreach loop cant find values of json object and display on php page

I got some data in my data/clients.json file and I'm trying to reach for some of the keys and values and display them in my php file. It does not work and i can not figure out why.
My clients.json file looks like:
{
"data": {
"nikajakubec": {
"name": "nika",
"loans": {
"amount": "1000",
"reason": "for garden"
}
}
}
}
And my PHP file:
<?php
$sData = file_get_contents('data/clients.json');
$jData = json_decode($sData);
$jClient = $jData->data->$sUsername;
foreach ($jClient->loans as $jLoans) {
echo "
<div>
<div>Amount:$jLoans->loans-></div>
<div>Reason:$sUserName->reason</div>
</div>";
}
?>
Do like this:-
<?php
$json = '{
"data": {
"nikajakubec": {
"name": "nika",
"loans": {
"amount": "1000",
"reason": "for garden"
}
}
}
}';
$jData = json_decode($json);
foreach ($jData->data as $user) {
echo "
<div>
<div>Amount:". $user->loans->amount ."</div>
<div>Reason: ". $user->loans->reason ."</div>
</div>";
}
Output:- https://3v4l.org/8HPV5
The field reason it's actually nested inside the loans prop, not directly in the user.
so instead of
$sUserName->reason
just go
$jLoans->reason
And also go $jLoans->amount instead of $jLoans->loans->
Consider that when you cycle $jClient->loans you are going to work on each prop of loans, which are 'amount' and 'reason'

submenus in php using json

<?php
$jsondata = file_get_contents('js/brand.json');
$data = json_decode($jsondata, true);
$menuonesublinks = $data['menuonesublinks']['links'];
foreach ($menuonesublinks as $menu_sublink) {
?>
<?php
echo $menu_sublink['title'];
?>
<?php
}
?>
o/p i am getting : usa,uk
how can i get inside subcities of city values ("subcities":[{"city":"dubai"},{'city':"london"}])
brand.json
{
"menuonesublinks": {
"links": [
{
"title": "usa",
"subcities":[{"city":"dubai"},{'city':"london"}]
},
{
"title": uk
}
]
}
}
You need to change your foreach loop in the following way,
// your code
foreach ($menuonesublinks as $menu_sublink) {
echo $menu_sublink['title'];
if(array_key_exists('subcities', $menu_sublink)){
foreach($menu_sublink['subcities'] as $subcity){
// Now access subcities like this: $subcity['city']
}
}
}
Here's the relevant reference:
http://php.net/manual/en/function.array-key-exists.php

To display output from mysql using PHP (json encode)

I'm trying to code a page like facebook-view_posts_page where I need to show the result as POST 1..Comment 1.. Comment 2.. POST 2.. Comment 3
The output of my code is
POST 1
POST 2
comment 1
comment 2
comment 3
How should I re write my code?
<?php
include("connect.php");
$userID=$_REQUEST['userID'];
$Query=("select * from tb_post where userID='$userID'");
$result=mysql_query($Query);
$count=mysql_num_rows($result);
if($count>0)
{
//$post['result']="sucess";
$joinQuery=("select * from tb_post where tb_post.userID='$userID'");
$joinResult=mysql_query($joinQuery);
while($row=mysql_fetch_assoc($joinResult))
{
$posts[]=$row;
$postid=$row['postID'];
$commentQuery=("select tb_comment.commentID,tb_comment.userID ,tb_comment.postID ,tb_comment.comment ,tb_comment.date,signup.userName,signup.image from tb_comment,signup where tb_comment.postID='$postid' and signup.userID=tb_comment.userID");
$commentResult=mysql_query($commentQuery);
//$post['posts']=$posts;
while($commentrow=mysql_fetch_assoc($commentResult))
{
$comments[]=$commentrow;
}
}
$post=array("result"=>"success","posts"=>$posts,"comments"=>$comments);
}
else
{
$post['result']="failed";
$post['error']="no data found";
}
$data='content-type:application/json';
$data=json_encode($post);
echo $data;
?>
I will explain you the approach.
You are fetching and appending comments in an array without any direct key reference to the post.
array comments;
while (comment = fetch comments) {
comments[post id][] = comment;
}
while showing:
while (post = fetch posts) {
echo post title;
foreach (comments[post id] as postComment) {
echo postComment;
}
}
Comments should have reference to the post as key of comments array.
In your case, you are already fetching comments correctly, just change the following inner while loop to:
while($commentrow=mysql_fetch_assoc($commentResult)) {
$comments[$commentrow['postID'][]=$commentrow; // Observe postID
}
Fully working code:
<?php
include("connect.php");
$userID=$_REQUEST['userID'];
$Query=("select * from tb_post where userID='$userID'");
$result=mysql_query($Query);
$count=mysql_num_rows($result);
if($count>0) {
$joinQuery=("select * from tb_post where tb_post.userID='$userID'");
$joinResult=mysql_query($joinQuery);
while($row=mysql_fetch_assoc($joinResult)) {
$posts[]=$row;
$postid=$row['postID'];
$commentQuery=("select tb_comment.commentID,tb_comment.userID ,tb_comment.postID ,
tb_comment.comment ,tb_comment.date,signup.userName,signup.image
from tb_comment,signup
where tb_comment.postID='$postid' and signup.userID=tb_comment.userID");
$commentResult=mysql_query($commentQuery);
while($commentrow=mysql_fetch_assoc($commentResult)) {
$comments[$commentrow['postID']][] = $commentrow;
}
}
$post=array("result"=>"success","posts"=>$posts,"comments"=>$comments);
}
else {
$post['result']="failed";
$post['error']="no data found";
}
$data='content-type:application/json';
$data=json_encode($post);
echo $data;
?>
You can print posts and its comments like this:
<?php
if (! empty($posts)) {
foreach ($posts as $post) {
echo $post['post_title_field'] . "<br/>";
if (! empty($comments[$post['postID']])) {
foreach ($comments[$post['postID']] as $postComment) {
echo postComment . "<br/>";
}
}
}
}
?>
Thanks everyone for helping me.My friend came up with another solution, which is the code I'm looking for.And here is the code:
<?php
include("connect.php");
$sel_post=mysql_query("SELECT * FROM tb_post WHERE userID='".$_REQUEST['userID']."'");
if(mysql_num_rows($sel_post)>0)
{
while($row=mysql_fetch_assoc($sel_post))
{
$sel_post_owner=mysql_query("SELECT name,image FROM signup WHERE userID='".$row['userID']."'");
if(mysql_num_rows($sel_post_owner)>0)
{
while($row_owner=mysql_fetch_array($sel_post_owner))
{
$row['post_owner_name']=$row_owner['name'];
$row['post_owner_image']=$row_owner['image'];
}
}
else
{
$row['post_owner_name']="";
$row['post_owner_image']="";
}
$sel_comments=mysql_query("SELECT * FROM tb_comment WHERE postID='".$row['postID']."'");
if(mysql_num_rows($sel_comments)>0)
{
$comments=array();
while($row_comment=mysql_fetch_assoc($sel_comments))
{
$sel_comment_owner=mysql_query("SELECT name,image FROM signup WHERE userID='".$row_comment['userID']."'");
if(mysql_num_rows($sel_post_owner)>0)
{
while($row_comment_owner=mysql_fetch_array($sel_comment_owner))
{
$row_comment['comment_owner_name']=$row_comment_owner['name'];
$row_comment['comment_owner_image']=$row_comment_owner['image'];
}
}
else
{
$row_comment['comment_owner_name']="";
$row_comment['comment_owner_image']="";
}
$comments[]=$row_comment;
}
$row['comments']=$comments;
}
else
{
$row['comments']=array();
}
$Post[]=$row;
}
$post=array("result"=>"success","Posts"=>$Post);
}
else
{
$post['result']="failed";
$post['error']="no data found";
}
$data='content-type:application/json';
$data=json_encode($post);
echo $data;
?>

PHP, Requesting from link and echoing json array

I have this code but it does not seem to be working. After entering an IP into the text field and hitting the button it will return with the page loaded up to the php code but will not load the php code result nor any code past it.
<?php
if(isset($_POST['resolve'])){
$api = "https://iphub.p.mashape.com/api.php?ip=";
$endbit = "&showtype=4";
if(strlen($_POST['name'])==0){
echo "fill in all fields!";
} else {
// assuming $_POST['resolve'] has an IP
// $response = file_get_contents($api.$_POST['name'].$endbit);
$response = Unirest\Request::get($api.$_POST['name'].$endbit,
array(
"X-Mashape-Key" => "U3sk6nAZzBmshyiHEUZHigxLGp1ZTZnKjsnkd8LWULJmRRp",
"Accept" => "application/json"
)
);
?>
<div align="center">
<?php
if($response['proxy'] == '0') {
echo 'No';
}
elseif($response['proxy'] == '1') {
echo 'Yes';
}
else {
echo 'Error.';
}
?>
</div>
<?php
}
}
?>
The API I am using requires me to have the header/X-Mashape-Key.

Categories