Select specific values from json_decode in php - php

I've stumbled on a problem that i think is a bit strange since i've followed other examples to the exact code but i still didn't get the same result.
Short summary
I'm developing a shopping application and i'm using a session for the cart. Since i want to have the possibility to remove items from the cart i am using some levels inside the JSON object of the session.
Cart summary
The cart is created on button click
$_SESSION['cart']["cartItems"][$product_id]=$cartProduct;
Where $cartProduct is an array() of items like the product_id, product_name, etc.
Where the cartlevel: $product_id is for the remove cart row function().
The cart is then shown in an angularJS application. I will pass the full view and just show the getCart section and the JSON response.
$json = json_encode($_SESSION['cart']['cartItems']);
echo($json);
The JSON echo is:
{"3":{"id":"3","name":"Bedrukte Jurk","price":25.99,"size":"M","quantity":"3","total_product_price":77.97},"2":{"id":"2","name":"Blouse","price":26.99,"size":"S","quantity":"3","total_product_price":80.97}}
The JSON is stripped by removing the ['cartItems'] value.
The $_SESSION['cart']'s original JSON object would be:
{"cartItems":{"3":{"id":"3","name":"Bedrukte Jurk","price":25.99,"size":"M","quantity":"3","total_product_price":77.97},"2":{"id":"2","name":"Blouse","price":26.99,"size":"S","quantity":"3","total_product_price":80.97}}}
{"cartItems":{"3":{"id":"3","name":"Bedrukte Jurk","price":25.99,"size":"M","quantity":"3","total_product_price":77.97},"2":{"id":"2","name":"Blouse","price":26.99,"size":"S","quantity":"3","total_product_price":80.97}}}
The question
So now i would like to select only the "name" ,"id" and other values seperatly since i have to write them to a database. it would be something like:
$json_test = json_decode($_SESSION['cart']['cartItems']['name']);
echo $json_test;
$product_name = $json_decode_name;
So at this moment my question really starts. i'm having one issue and one real question on how ould i achieve this (thinkin of using foreach()
So first my problem is that i can't, or i am not able to select the specific values from the json cart session. I've tried some things from the PHP docs and made a small comparison:
$json1 = '{"foo-bar": "123", "foo-bar2": "456"}';
echo($json1);
echo "<br>";
$obj = json_decode($json1);
print $obj->{'foo-bar2'}; // 456
echo "<br>";
$json_decode = json_decode($_SESSION['cart']['cartItems']['3']);
print $json_decode->{'name'};
echo "<br>";
var_dump(json_decode($_SESSION['cart']['cartItems']['3'], true));
echo "<br>";
$json = json_encode($_SESSION['cart']);
echo($json);
The $json1 is working but i can't quite get my own version working.
Some extra tips?
The second thing is then pushing it to the database. I was thinking about: when achieving the name / names from the JSON string i would use a foreach() statement. Something in the area of:
$cart_product_name = $json_decoded_name
foreach ($cart_product_name as $product_name) {
insert_Query
}
And repeat this for the id's, quantity's, etc.
If the question isn't clear please let me know in the comments and i'll edit it.
As always, Thanks in advance!

Related

Steam Inventory in PHP from json

so basically Im trying to get steam player inventory in PHP from geting json content but I cannot figure out how to do it, espcially I didn't work with json a lot before. I have a problem with what I should pick in PHP to get what I want from the JSON.
PHP:
$inventoryJsonUrl = 'http://steamcommunity.com/inventory/'.$steamID.'/730/2?l=english&count=5000';
$inventoryJsonGet = file_get_contents($inventoryJsonUrl);
$inventory = json_decode($inventoryJsonGet, TRUE);
for ($i=0; $i < count($inventory['assets']) ; $i++) {
echo $inventory['assets'];
}
And lets say the $inventoryJsonURL is now http://steamcommunity.com/inventory/76561198260345960/730/2?l=english&count=5000
And I have problem with getting what I want, I mean lets say that in the for loop I want to have name of the item/skin, id of that item and some more things. But I don't know how and what I suppose to pick to get that.
Sorry for bad bad English.
Thanks in advance.
You can make use of PHP's foreach loop.
$inventories = json_decode($inventoryJsonGet , TRUE);
// you can check the structure of your array by
// print_r($inventories)
foreach ($inventories['descriptions'] as $key => $description) {
echo '<pre>';
echo $description['appid'];
echo $description['market_name'];
echo '</pre>';
}
The endpoint contains two lists: assets and descriptions. It's hard to offer some help if you don't really know what you are looking for. I think what you are looking for is descriptions, as there is all the data. See here for the first item: https://www.dropbox.com/s/z736vu6boh9rfi6/steam1.gif?dl=0
Seems as tho that is a shotgut from Counterstrike GO.
Also, this article may help you a bit: Getting someone's Steam inventory
And as a start, I suggest to beautify the content of that json, so you have a better overview of what's in there. I usually use https://codebeautify.org/jsonviewer but there are several other.

PHP making a Forum with a database, can't get the links working

So i am making a simple forum to learn some PHP with CodeIgniter, by simple i mean 1 page with posts and you can click on them to comment and view more info(Think of reddit). All the data is stored in a mySQL database. Anyways i got all the links to display on my page, but what i cant figure out is how to open a new page to show the description and comments of the post. I remember doing something similar with a long time ago, can't remember how i did that sadly.
<?php
foreach($records as $rec){
$test = $rec->PostName."<br/>";
Echo "<a href=#$test>$test</a>";
}
?>
<?php
echo '<div data-role="page" id="$test"></div>';
echo "THIS ISSSSS $test";
?>
So this is the part where i need help. Any suggestions are greatly appreciated
Well for starters you'll need to refactor your attempt at generating the links as that has issues as everyone has pointed out.
So I took the liberty to come up with some test code to demonstrate a few things.
So this is Part 1.
<?php
// Simulated Database results, an array of objects
//
// These may already be Slugs with First letter upper case, hyphenated between words
// But I will do that when generating the links.
$records = [
(object)['PostName'=>'Why I recommend reading more PHP Tutorials'],
(object)['PostName'=>'Why I should take heed of what others suggest and actually try them out before dismissing them'],
(object)['PostName'=>'What is the difference between using single and double quotes in strings'],
(object)['PostName'=>'Why everyone should know how to use their browsers View Source tool to inspect the generated HTML'],
];
foreach ( $records as $rec ) {
$test = $rec->PostName;
// This would make a good helper but Codeigniter might have something already.
// So you should go and read the manual.
echo "$test";
// The above uses " to wrap the string with escaped \" within the string
// cause you cant have both.
echo '<br>';
}
// This is only here for testing... I think.
echo '<div data-role="page" id="'.$test.'"></div>';
// The above uses single quotes to wrap the string.
echo "THIS ISSSSS $test";
Part of Part 2...
<?php
// Simulated Database results, an array of objects
//
//
// These may already be Slugs with First letter upper case, hyphenated between words
// But I will do that when generating the links.
$records = [
(object)[
'id'=>1,
'PostName'=>'Why I recommend reading more PHP Tutorials'],
(object)[
'id'=>2,
'PostName'=>'What is the difference between using single and double quotes in strings'],
];
foreach ( $records as $rec ) {
$name = $rec->PostName;
$id = $rec->id;
// The slug of the page isn't really being used here as
// we are providing the pages id for lookup via an AJAX Call.
echo "<a id=".$id." href=\"#".ucfirst(str_replace(' ','-',$name))."\">$name</a>";
echo '<br>';
}
// This is where the AJAX call fired by a click on an anchor, that sends the id
// which results in the fetching of the required details to plonk in our page-area div.
echo '<div class="page-area"></div>';
There are a number of ways to do this, but going totally basic, if we create a JS event for a click on an anchor.. Which fires an AJAX Call which posts the page id to our method that returns back the HTML of the results we want to display...

Pulling title from API

Alright so I started with something simple just to get me familiar with what exactly I am getting my self into, how ever when tinkering I became lost.
Okay so I am trying to get contents from the following
$details = json_decode(file_get_contents("https://beam.pro/api/v1/users/63662"));
what's the best way I can go about doing this?
Currently I can display the username portion using print $details->username; and the id portion using print $details->id; but after this I become lost how could I go about pulling the title for example.
Here is what the Twitter looks like currently in the API
"name":"Thursday -- BR 2's [NA] w/ beam.pro/para",
Documentation is here
You would use the following:
echo $details->channel->name;
However, if you're more comfortable with arrays, you could do this:
$details = json_decode(file_get_contents("https://beam.pro/api/v1/users/63662"), true);
echo $details['channel']['name'];
Here is the object structure for future reference:

retrieving data from database with php and send to another page

I am now trying to create a page which shows restaurants in a list for people to comment and rate, the restaurant info is in the database. I've already get the data I want using while() function, but I am struggling to pick one of them and pass to another page. Below is my code. I tried to use sessions to store the data, like the "$_SESSION['rid']" for storing the restaurant ids. I have 8 rows in the restaurant table, and when I click on the first restaurant, the number shows on the other page is 8.
<?php
$sql_restaurant = "select * from tbl_restaurants";
$results = mysql_query($sql_restaurant);
while($restaurant_row=mysql_fetch_assoc($results)){
$_SESSION['rid'] = $restaurant_row['restaurant_id'];
echo "<a><span style = 'color:black'>".$restaurant_row['restaurant_name']."</span></a>";
echo "<dd>";
echo "<a><span style = 'color:black'>".$restaurant_row['restaurant_address']."</span></a>";echo '</dd>';
echo '<i class="mod_subcate_line"></i>';
echo 'Rate it!';
echo 'Comment!';
echo '<br/>';
echo '<br/>';
}
?>
I want it to show the right restaurant id when I click on different restaurants. How can I solve this?
Right now your code is changing $_SESSION['rid'] every time you cycle through the loop. So it will have the last cycle of the loop.
You shouldn't do this with sessions, always keep in mind that HTTP is a stateless system and sessions are stateful. It's always better to not rely on state.
As mentioned in the comments, you should write the restaurant ID as part of the URL of the link in a query parameter that you can then access through the $_GET array.
If you want to use $_SESSION, choose a different name for every loop. Here, $_SESSION['rid'] get the value of the last loop.

PHP Cart with Object Oriented PHP

I am developing a simple system of sample products with Object Oriented PHP, very simple thing. So far, no problem, but I have to create a button that adds a product code recorded in the database to a form in the sidebar. I do not know to develop a shopping cart with OO PHP, and codes that I find always give error because of the call of the database, or when the data list. I've been thinking of doing for JS, any help?
sorry my bad english
I got it, first I did when I click a link step by GET and the ID Code I need after seto it in a cookie, each cookie with an ID. Then I check if cookie has registered with the IDs. Not the best and most correct, but it works (more or less). Now another problem, I need to click two times to get the result as it passes by id and need to be caught refresh = /
I think it was a bit confusing but it is the maximum that dyslexia allows me to do hehehe
Here I set up the structure with the data I have in my product page:
add
<?php
$cod_get = $_GET['cod'];
setcookie("SITENAME_cod_".$id_get."", $cod_get, time()+3600, "/","", 0);
?>
And here I have a loop checking if cookie with ids, I think it will give problems, but for now I think it works ...
Thank you all.
$produto = new produtos();
$i = 0;
$produto->selecionaTudo($produto);
$produto->selecionaCampos($produto);
while($res = $produto->retornaDados()):
$res->id;
$i++;
$get_cookie = $_COOKIE['SITENAME_cod_'.$res->id.''];
if (isset($get_cookie)) {
echo $get_cookie.', ';
}else{
echo "";
}
endwhile;

Categories