Encoding Json Correctly? - php

Alright, So I'm redoing my question so people can understand what I'm trying to do.
Search.php
<?php
$getItems = file_get_contents('Items.json');
if(isset($_GET['searchVal'])){
$getItems2 = json_decode($getItems, true);
$data2 = array("items" => array(array()));
foreach($getItems2['items'] as $data){
if(strpos($data['name'], $_GET['searchVal'])){
$data2 = array("items" => array(array($data)));
}
}
echo json_encode($data2,JSON_UNESCAPED_SLASHES);
} else{
echo $getItems;
}
Problem: Doesn't get all items which have that name, gets only one.
Search is done, now I have to fix somehow to get all items which match the name. How could I do that?

You have the following inside a loop:
$data2 = array(...)
...and then you reference $data2 outside the loop.
Of course, it will only contain the last entry, because that line is overwriting $data2 with new data each time the loop iterates.
If you want to keep all the records from the loop, use
$data2[] = array(...)
instead.
[EDIT]
Further guessing as to what you actually want your JSON to look like, I guess you want all the records to be in the items array?
So in that case, let's rewrite your $data2 line, as follows:
$data2['items'][] = array($data);
This will add all the data arrays to your items array in $data2. I will note that your array structure is really convoluted -- too many nested arrays, which makes it difficult to be sure I'm giving you the answer you want even now, but hopefully if it isn't exactly right, it will show you the direction you need to go.
You'll also want to have an additional line at the top of your code to initialise $data2, like this:
$data2 = array('items'=>array());
This should be somewhere at the top of the code, before $data2 is used, and outside of the loop.

Related

PHP extract key-value in array json and restructure

Any idea on how to restructure the json below:
$jsonArray = [{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]
Expected outcome:
$expected = {"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
I'm new and my thinking is get the product value in array and again use foreach loop to find the others value? .
Here's one possibility:
$jsonArray = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$output = array();
foreach (json_decode($jsonArray, true) as $row) {
$product = $row['Product'];
$output[$product] = $row;
unset($output[$product]['Product']);
}
echo json_encode($output);
Output:
{"Milk":{"Level":"77.2023%","Temperature":"4"},
"Coffee":{"Level":"399.2023%","Temperature":"34"},
"Chocolate":{"Level":"109.2023%","Temperature":"14"}
}
Demo on 3v4l.org
This made some trick
$a = '[{"Level":"77.2023%","Product":"Milk","Temperature":"4"},
{"Level":"399.2023%","Product":"Coffee","Temperature":"34"},
{"Level":"109.2023%","Product":"Chocolate","Temperature":"14"}]';
$newAr = array();
foreach(json_decode($a,true) as $key=>$value)
{
$newAr[$value['Product']] = array(
'Level' => $value['Level'],
'Temperature' => $value['Temperature'],
);
}
There are many ways to perform this with Loops in PHP. Other answers demonstrate it accurately. I would also suggest to integrate some form of Error handling, data validation/filtering/restriction in your code to avoid unexpected results down the road.
For instance, json_decode(), either assigned to a variable pre-foreach or straight in the foreach() 1st argument will just raise a warning if the original json is not valid-json, and just skip over the foreach used to construct your final goal. Then if you pass the result (that may have failed) directly to your next logic construct, it could create some iffy-behavior.
Also, on the concept of data-validation & filtering, you could restrict the foreach(), or any other looping mechanism, to check against a Product_List_Array[Milk,Coffee,Chocolate], using if(in_array() ...) so the final/goal object only contains the expected Products, this, in the case the original json has other artifacts. Filtering the values can also increase stability in restricting, for example, Temperature to Float.

Array is reassigning previous values into unset locations, PHP

I am trying to create a multidimensional array at run-time that queries and stores several MySQL results. For instance, let us say we have a table like so (is fictional, so please don't pick at the example):
**store--tag--color--size**
1--101--blue--s
2--102--red--s
2--103--yellow -- m
3--104--blue--m
The need is to create an multi-d array that will store all the products per store. The result I would like is:
$storeArray = array[[[101],[blue],[s]],[[102,103],[red,yellow],[s,m]],[[104],[blue],[m]]];
here is the code I have:
$counter = 0;
foreach($storeIDs as $item){
$result = mysql_query('select whatever');
$rows = mysql_num_rows($result);
for($i=0;$i<$rows;$i++){
$tag[$i] = mysql_result();
$color[$i] = mysql_result();
$size[$i] = mysql_result();
}
$tempArray = array($tag,$,$color,$size);
$storeArray[$counter] = $tempArray;
unset($tempArray);
$counter++;
}
The problem is, even though I have unset $tempArray, the third loop which should capture just
[[104],[blue],[m]]
actually stores
[[104,103],[blue,yellow],[m,m]].
I've tried setting $tempArray to array(), or array(array()). The data from the second loop always spills over into ANY future iteration that is of smaller size.
How can I get $storeArray to look like the goal above?
Thank you
You're unsetting $tmpArray, but it looks like you may need to also unset $tag, $color, and $size as well. There are better approaches with a slightly different data structure, but as is, have you tried this?
unset($tempArray,$tag,$color,$size);
Effectively, you might set $tag[0] and $tag[1] in a loop that has two items. Then, for a loop that has one item you update $tag[0], but $tag[1] remains set.

PHP array modification

I have a file containing a two dimensional array and the first term of each nested array is of form id=>2.
I want to extract the array into another file, find the last id in the array, add one to it, create a new array element containing that new id term, add it to the array and then save the edited array back to the original file.
This seemingly simple task has got me beat. I can do the whole thing as long as the processing is done within the original file and I can use file_get_contents() to get the contents of one file into another. But then if I try to use any of the contents I've extracted, eg the array name, php tells me it is undefined.
Grateful if someone could give me a pointer on how to do this.
include 'thefile.php';
$id = 0;
foreach($thearray as $item){
if($item['item_id'] > $id) $id = $item['item_id'];
}
$id++;
$thearray[] = array('item_id' => $id);
file_put_contents('thefile.php','<?php $thearray = '.var_export($thearray, true).';');

create a multidimensional array in a loop php

I've done a fair bit of googling and couldn't find anything that works, I'm just getting nothing back, this is probably something simple but there's a lot of variations that don't seem to match what I'm doing.
To give you an overall idea what I'm at, I'm accessing an API and getting back info as an object. There are comments and attachments, these are in separate arrays.
What i want to do is display the comments and attachments all together in the order of the date and time not separately.
I figured the best way is to create a loop through the comments array, then create a loop through the attachment array, then join both and sort by the date (epoch) and then loop through the whole merged loop echoing what i want. That should provide some context, right now i just want to create the multidimensional array for comments and i can figure out the rest.
$comments_holder = array();
//total number of comments in the array
$comment_total = $issue_json->fields->comment->total -1;
$i=1;
while ($i <= $comment_total)
{
//this is the date,time and timezone info for each comment
$raw_date = $issue_json->fields->comment->comments[$i]->updated;
$comments_holder[$i] = array();
//convert_sql_time just converts from 2012-11-04T16:33:00.936+600 into epoch time so i can sort the results later based on date
$comments_holder[$i]['comments_date'] = convert_sql_time($raw_date);
$comments_holder[$i]['comments_displayName'] = $issue_json->fields->comment->comments[$i]->author->displayName;
$comments_holder[$i]['comments_body'] = $issue_json->fields->comment->comments[$i]->body;
}
if everything is okay with data, this code will be enough for building such array:
$comments = $issue_json->fields->comment->comments;
$result = array();
foreach ($comments as $comment) {
$result[] = array(
'comments_date' => convert_sql_time($comment->updated),
'comments_displayName' => $comment->author->displayName,
'comments_body' => $comment->body,
);
}
print_r($result);
if comment->comments is an array, there is no need to keep it's count separately;
foreach is enough for iterating through the array and there is no need to keep separate variable for calculating array index;
[] notation will automatically increase array index and assigning array directly will do the trick(i.e. will result to multi dim array)

Problem with associative arrays

I have always sucked at complex arrays there must be something in my brain preventing me from ever understanding them. I will try to make this example really simple so we will not go off topic. I use this code to use numbers to represent each file name:
$mod_nums = array('1' => $input_zip_path . '01_mod_1.0.2.zip',
'2' => $input_zip_path . '02_mod_1.0.1.zip',
);
So when I use $mod_nums['01'] it will display the path to that file. I have an array from the script that put these $mod_nums values into an array like so:
$files_to_zip = array(
$mod_nums['1'],
$mod_nums['2']
);
That worked fine. Now I wanted to add a $_POST value so that I can enter numbers like 1,2 and other numbers that I add to the $mod_nums array later like 1,3,6,12 for example. So I used an explode for those posted values:
$explode_mods = explode(",", trim($_POST['mods']));
Now for the big question that is racking my brain and spent hours on and cannot get it to work.... I need for $files_to_zip to still be in an array and display the posted values of $mod_nums. So it would be like:
$files_to_zip = array( HAVE $_POSTED VALUES IN HERE );
I hope that makes sense. I need $files_to_zip to remain in array format, grab the file path to the zip files from the $mod_nums array, and display it all correctly so it would dynamically output:
$files_to_zip = array('01_mod_1.0.2.zip', '02_mod_1.0.1.zip');
so posted numbers will appear in an array format for the $files_to_zip variable. Make sense? In short I need an array to have dynamic values. Thanks :)
EDIT
Phew I figured it out myself from memory when I worked on something similar many years ago. This looks tough but it isn't. I had to use a foreach and assign the variable into an array like so:
$blah = array();
foreach ($explode_mods as $value)
{
$blah[] = $mod_nums[$value];
}
then I just assigned $files_to_zip to $blah:
$files_to_zip = $blah;
works perfectly :) I just forgot how to dynamically assign values into an array.
// filenames array
$mod_nums = array('1' => $input_zip_path . '01_mod_1.0.2.zip',
'2' => $input_zip_path . '02_mod_1.0.1.zip',
);
// mod_num keys
$explode_mods = explode(',', trim($_POST['mods']));
// array to hold filenames
$files_to_zip = array();
// loop over all the mod_num keys submitted via POST
foreach($explode_mods as $key){
// save the filename to the corresponding array
$files_to_zip[] = $mod_nums[$key];
}
maybe i havn't understood you right, but won't this just be a simple foreach-loop to add the entrys to $files_to_zip like this:
$explode_mods = explode(",", trim($_POST['mods']));
foreach($explode_mods as $k){
$files_to_zip[] = $mod_nums[$k];
}

Categories