Proper way to push values to an array PHP? - php

I have run into a problem that is a little irritating. Here is my PHP code. Ignore where the variables are coming from. This is for shopping-cart functionality but it is applicable in many different areas.
$data_set = json_decode(stripslashes($_POST['varA']), true);
$pid = $pid['product_id'];
$quantity = $pid['quantity'];
$_SESSION['cartid'] = $_SESSION['cartid'] + 1;
$product_data = array("Product_ID" = > $pid, "quantity" = > $quantity, "cartid" = > $_SESSION['cartid']);
My issue is occurring at this place in the code. I first check to see if the Session variable has a value in it, if not then it proceeds to create an associative array.
if (empty($_SESSION['cart_items'])) {
$_SESSION['cart_items'] = array("items" = > $product_data);
} else {
array_push($_SESSION['cart_items']['items'], $product_data);
}
echo json_encode($_SESSION['cart_items']);
The end result after the first item is "added" looks like this:
{
"items": {
"Product_ID": "2",
"quantity": "1",
"cartid": 1
}
}
However, after several the first add, every value gets a key:
{
"items": {
"0": {
"Product_ID": "2",
"quantity": "1",
"cartid": 2
},
"1": {
"Product_ID": "2",
"quantity": "1",
"cartid": 3
},
"Product_ID": "2",
"quantity": "1",
"cartid": 1
}
}
How do I prevent these keys from occuring? Is this possible? If not, how can this be re-written so that the keys are added every time? And is this possible to parse and loop through in JS on the front end?
Sorry I have so many questions. Any help is really appreciated.

In the first iteration, the $_SESSION['cart_items'] is empty, so you run this:
$_SESSION['cart_items'] = array("items" => $product_data);
This creates $_SESSION['cart_items']['items'] but you populate it with just the product by itself; you should define it as an array instead:
$_SESSION['cart_items'] = array("items" => array($product_data));
This creates an array with a single item which you can later extend with array_push.
Having said that, you can replace the whole condition with just:
$_SESSION['cart_items']['items'][] = $product_date;
PHP will automatically create an empty array if it didn't exist yet, followed by adding the product data as the next element.

This is because of this line:
$_SESSION['cart_items'] = array("items" = > $product_data);
You essentially say in that line that 'items' key has product data, instead of key in items. It should be:
$_SESSION['cart_items']['items'] = array($product_data);
Keys -will- always occur, unless you want data to overwrite another. If you do not want keys (0,1 etc) then the only other option is merging data. In which case it would be:
$_SESSION['cart_items']['items']+=$product_data;
..but I don't think that is what you want.

You don't need the items, try the below way.
if (empty($_SESSION['cart_items'])) {
$_SESSION['cart_items'] = array($product_data);
} else {
$_SESSION['cart_items'][] = $product_data;
}

Related

How to get a specific value from a json array out of a list of arrays

everyone, I was just trying to find out a way to get the value of a link from a JSON array , after I have searched the array with help of Id. I am using PHP's file_get_contents and the webpage from which information is to be taken looks like
[{
"id":"2972",
"name": "AbC",
"link":"any link",
"epg": "any link",
"dur": "disabled",
"language": "y",
"category": "TOP 100",
"logo": "any url here"
},
{
"id": "1858",
"name": "Efg",
"link": "url",
"epg": "url",
"dvr": "disabled",
"language": "E",
"category": "TOP 100",
"logo": "url"
}]
From here suppose I have been given an Id 1858 so I have to find a link from the array of Id having 1858
I am a beginner in PHP and was just fidgeting around with a piece of code and tried to get its solution and a big Thanks To You For Your Answer and valuable Time.
if you are using file_get_contents('php://input'); then you should try this to access json data
$json = file_get_contents('php://input'); //get json data in variable
$array = json_decode($json); //parse json data in php array
// assecc the array with use of foreach loop
foreach($array as $obj){
//access the json element here like $id = $obj->id; $url = $obj->link;
//if you want to check the id value in array you can compare value with if condition
$id = $obj->id;
// find link for specific id
if($id =='1858'){
$url = $obj->link;
echo $url; // do something with link
//you can use break; statement if you found your element and terminate the loop
}
}
You can use array_column, to map pairs of json keys/values:
<?php
$json ='
[
{
"id": 3,
"link": "http:\/\/example.com\/3"
},
{
"id": 5,
"link": "http:\/\/example.com\/5"
}
]';
$data = json_decode($json, true);
if($data !== null) {
echo array_column($data, 'link', 'id')[5] ?? null;
}
Output:
http://example.com/5
To understand this we can see the result of array_column.
var_export(array_column($data, 'link', 'id'));
Output:
array (
3 => 'http://example.com/3',
5 => 'http://example.com/5',
)
So with the above code, we are checking for and outputting the associated index of 5 (the original id).

Search a value in JSON using PHP

<?php
$str = '[
{
"node":{
"id": "bitcoin",
"name": "Bitcoin",
"price_usd": "610.471"
}
},
{
"node":{
"id": "ethereum",
"name": "Ethereum",
"price_usd": "12.0771"
}
}
]';
$result = json_decode($str, true);
$key = array_search('bitcoin', array_column($result,'node','id'));
echo $result[$key]['price_usd']; // i need 610.471 here
?>
I have a long json code like above, I need to get the "price_usd" value by searching "id" name.
i dont want $str[0]["node"]["price_usd"]
Just iterate over the array and break when you get a hit:
foreach ($result as $k => $v) {
if ($v['node']['id'] == 'bitcoin') break;
}
echo $result[$k]['node']['price_usd'];
The above code assumes that each sub-array has a key called node which also contains a key called id. If you can't rely on those things you need to check on each iteration. I also assume you only need one value (the first one) since there could easily be multiple instances of id being equal to bitcoin
You can use a double array_column() in order to get the list of prices by id:
$prices_by_id = array_column(array_column($result, 'node'), 'price_usd', 'id');
This is needed because of the multiple nested levels in the original JSON string.
The value of $prices_by_id:
array(2) {
["bitcoin"]=>
string(7) "610.471"
["ethereum"]=>
string(7) "12.0771"
}
This way you can use $prices_by_id['bitcoin'] to get its price.

Unset all data except the data associated with a given value in url

I have a file that sends a request through curl, when I hit the url which is formatted as http://www.example.com/api/something?id=24 I get a series of arrays back in JSON form. It looks like:
24: {
pe: {
id: "24",
name: "Blah",
engine_src: "blah",
each_lender: "1",
soap_request: "0",
lenders: {
0: "3",
1: "1",
2: "6",
3: "12"
}
},
lenders: {
0: {
id: "1",
platform_id: "2",
lender_id: "3",
engine_id: "24",
status: "1",
engine_lender_id: "3",
engine_lender_name: "choice #1"
},
}
There are several other numbers and arrays in the list that look similar. I need to return the array that is associated with the id in the url and only that array.
I have set a new variable which looks like
$selected = (int)$_REQUEST['pe'];
How do I unset all other values except what is in my $selected variable?
Ok, then, assuming your response is in the variable $jsonresponse...
$selected = json_decode($jsonresponse,$assoc=TRUE);
$selected = $selected[$id];
Thank you for your help Charlene. This is how I ended up solving the problem. It is the same concept that Charlene posted just a slightly different format.
$selected = (int)$_REQUEST['pe'];
$save_me = $data[$selected];
unset($data);
$data = $save_me;
print_r($data);

php parsing json using value from list

I have a json like this:
"achievementsProgress": [
{
"value": 11,
"globalID": 23000000
},
{
"value": 11,
"globalID": 23000001
},
{
"value": 11,
"globalID": 23000002
},
{
"value": 147,
"globalID": 23000003
},
{
"value": 147,
"globalID": 23000004
},
{
"value": 147,
"globalID": 23000005
},
.....
]
It goes on like that and I need to be able to read the "value" field of every 3rd.
So globalID 23000002, 23000005, 23000008, 230000011 etc. All the way up to and including 65. And then I need to save those as variable names like:
$achievement1 for globalID 23000002
$achievement2 for globalID 23000005
etc.
Now I assume this has to be done in a loop.
So far I have this much.
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true)
and it would be
$data['achievementsProgress'] to get to the list of the above json.
How would I go about doing this?
Here is one way to do it. I think any way you'll be able to do this will need to involve variable variables.
$x = 1; // start a counter for your variable names
for ($i=2; $i < 65; $i+=3) { // start at index 2 (3rd value) and increment by 3
if (isset($data['achievementsProgress'][$i])) { // just in case there aren't actually 65
// Use variable variables to create the $achievement variables you want
${"achievement$x"} = $data['achievementsProgress'][$i]['value'];
}
$x++;
}
This example uses complex string syntax to create the variable variable.
Better do it like this:
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true);
$items=$data->achievementsProgress;
$result=[];
$i=1;
foreach($items as $item)
if($i++%3==0)
$result[$item->globalID]=$item->value;
//now $result contains map of data you wanted globalid => value
Now you can access it like this:
$result['23000000'] == 11 and so on

Seperate treatment of last/first entry in loop (that has a subloop)

I have some troubles with the following situation. I want to output nested information that looks a bit like this:
"name": "X",
"children": [
{
"name": "categories",
"children": [
{
"name": "Cat A",
"children": [
{"name": "B"},
{"name": "C"},
{"name": "D"}
]
},
{
"name": "Cat B",
"children": [
{"name": "C"},
{"name": "D"}
]
}
In this case you see that the last } of child Cat A has an comma at the end, while the last nest (Cat B) does not have comma at the end. In a previous topic I learned how to resolve the comma within the the inner loop ({"name": "D"}). However, using the implode (with sprintf instead of printf) at the end of the first while loop (see code below) created double prints of the data.
This is what the code looks like (slightly adjusted):
while ($ucs = mysqli_fetch_object($uc))
{
printf('{');
printf('"name": "%s",', $ucs->cat);
/*for ($i = 0; $i < 100; $i++)
{
$cat_name = $ucs->cat;
}*/
printf('"children": [');
$rtitle = "SELECT title FROM table WHERE genre='$category'";
//Some other code of lesser relevance for this issue
$names = array();
while ($title2 = mysqli_fetch_object($ptitles)) {
$names[] = sprintf('"name": "%s"', $title2->title);
}
echo implode(',', $names);
printf(']');
printf('},');
//Some other code
Now the main issue is to have the comma out of the last print statement.
However, using implode for the category did not work out. In the previous topic a user pointed me out to add it before the code if it isn't the first output. However, would that work in this scenario? If so, how could I flag whether this is the first iteration?
I hope someone can help me out here,
Help is again very much appreciated,
Thanks in advance!
At the beginning of your loop set a variable to 0 and at the end of the loop increment it by 1. Then, use an if statement to see if the variable is equal to 0.
Use json_encode(), though. It will lead to cleaner, more maintainable code.

Categories