PHP/MYSQL: Access data in Array of Dictionaries - php

I receive a JSON stream from an iphone that contains some simple strings and numbers as well as an array of dictionaries. I would like to work with these dictionaries, in essence, storing the data in each of them in a separate MYSQL record.
To get access to the strings as well as the array from the JSON stream, I am using the following:
$jsonString = file_get_contents('php://input');
$jsonArray = json_decode($jsonString, true);
$authString = jsonArray['authstring'];
$itemsArray = $jsonArray['itemsArray'];
This is what itemsArray looks like before being sent to the server:
itemsArray = (
{
lasttouchedstr = "2018-07-09 17:24:56";
localiid = 6;
iid = 0;
title = "test";
complete = 1;
userid = 99;
whenaddedstr = "2018-06-21 14:10:23";
},
{
lasttouchedstr = "2018-07-09 17:24:56";
localiid = 37;
iid = 0;
title = "how about this";
userid = 88;
whenaddedstr = "2018-07-07 16:58:31";
},
{
lasttouchedstr = "2018-07-09 17:24:56";
localiid = 38;
iid = 0;
title = reggiano;
userid = 1;
whenaddedstr = "2018-07-07 17:28:55";
}
etc.
I guess I should probably put these dictionaries into an Associative Array in order to save them.
I am struggling, however, with how to reference and get the objects. From what I can tell the following code is returning empty values in so far as $message comes back as empty.
$anitem = $jsonArray['itemsArray'][0];
$message=$anitem;
$title = $jsonArray['itemsArray'][0].[item];
$message.=$title;
Can anyone suggest proper syntax to grab these items and their properties?
Thanks in advance for any suggestions.

I find it strange that people associate things with a dictionary, while it is nothing more then a multidimensional array.
If you can read JSON, you see that the variable will have an index containing each entry.
For PHP:
foreach($jsonArray as $array){
// note that $array is still an array:
foreach($array as $v){
echo "Hurray!: '$v'";
}
}
If it really was an object (or cast to an object), the only thing you need to change is how you access the variable (as in any other language). In PHP it would be:
echo $jsonArray[0]->lasttouchedstr;
Or of it was the same loop:
foreach($jsonArray as $v){
echo $v->lasttouchedstr;
}
Multidimensional?
echo $jsonArray['itemsArray'][0][item]; // array
echo $jsonArray->itemsArray[0][item]; // if items array is an actual array and jsonArray an object.
Most languages associate things written as a . that the left side is an object. In PHP it's written as ->.

Related

php filtering json file and returning an attribute value

I have a json file which I read in. I want to first filter the json data to return the object defined by the datasetID, then get out the datasetName. I have filtered in javascript, but would prefer to stay in php but I can't figure it out, any ideas?
note: foreach is not required as only a single record is returned when filtered using the datasetID. So rather than using a foreach method how would you swelect a single record, first for instance?
$datasetID = '5fd4058e5c8d2'; // unique 13 character string
$data = json_decode(file_get_contents(path/to/file), True);
So I need to first filter for the unique object with $datasetID = '5fd4058e5c8d2';
$filtered_data =
Then I need to return the attribute datasetName from that object
$datasetName =
pointers to the best ways to do this is welcomed.
Sample json data:
[
[
{
"datasetID":"5fd4124900827",
"institutionCode":"None",
"collectionCode":"None",
"datasetName":"None"
}
],
[
{
"datasetID":"5fd4058e5c8d2",
"institutionCode":"None",
"collectionCode":"None",
"datasetName":"None",
}
]
]
I don't know how you got that JSON but it is nested deeper than needed. You can merge the top level arrays to flatten it, then index on datasetID:
$data = array_merge(...$data);
$filtered_data = array_column($data, null, 'datasetID')[$datasetID];
$datasetName = $filtered_data['datasetName'];
Shorter:
$filtered_data = array_column(array_merge(...$data), null, 'datasetID')[$datasetID];
$datasetName = $filtered_data['datasetName'];
Or to keep them all to use:
$data = array_column(array_merge(...$data), null, 'datasetID');
$datasetName = $data[$datasetID]['datasetName'];
I tried with your sample JSON.
First, json_decode will return a PHP array to use foreach on it. I wrote a simple foreach and checked your searching ID is equal to element's datasetID. If it is equal this is the datasetName you are searching for.
<?php
$json = '[[{"datasetID":"5fd4124900827","institutionCode":"None","collectionCode":"None","datasetName":"None"}],[{"datasetID":"5fd4058e5c8d2","institutionCode":"None","collectionCode":"None","datasetName":"None"}]]';
$elements = json_decode($json,TRUE);
$searchingID = "5fd4058e5c8d2";
foreach ($elements as $element) {
if(isset($element[0]['datasetID']) && $element[0]['datasetID'] == $searchingID){
$filtered_data = $element[0];
break;
}
}
echo $filtered_data['datasetName']; // or return $filtered_data['datasetName'];
?>

want to convert a key value pair to standard class object

Hi I need help [this is my table structure] and my current [JSON response is like this] and I want to convert this to [like this JSON response]
Can anybody give some idea or any related code so that I can make my JSON response like that.
*Note I can't create another table to store user images
First you don't need to concatenate your base_url to all images, you can use it separately in your front file, unless it must be there.
Second you don't need to store user_id to your image structure, because you have id right in your table's structure.
anyway you can do something like snippet below.
I hope it works fine :)
Edit:
It is easier to work with arrays in PHP so I convert my code to array version and if you need to use object first convert your object to array and after snippet you can convert it to object like (object) $data
foreach ($data as &$user) {
if(!empty($user['main_image'])) {
$user['main_image'] = $image_basepath . $user['main_image'];
}
$user['image'] = [];
for($i = 1; $i <= 6; $i++) {
$imgArr = [];
$img = $user['optnl_img' . $i];
unset($user['optnl_img' . $i]);
if(isset($img) && !empty($img)) {
$imgArr['id'] = $i;
$imgArr['user_id'] = $user['id'];
$imgArr['image'] = $image_basepath . $img;
}
$user['image'][] = $imgArr;
}
}

Looking for an element in an array in PHP

I don't know if I'm managing this array in the best way.
The array I have is this:
$bass = $_POST['bass'];
$selected_scale = $_POST['scale'];
$major_scales = array
(
array("C","D","E","F","G","A","B","C","D","E","F","G","A","B",),
array("C#","D#","E#","F#","G#","A#","B#","C#","D#","E#","F#","G#","A#","B#",),
array("Db","Eb","F","Gb","Ab","Bb","C","Db","Eb","F","Gb","Ab","Bb","C",),
array("D","E","F#","G","A","B","C#","D","E","F#","G","A","B","C#"),
array("D#","E#","F##","G#","A#","B#","C##","D#","E#","F##","G#","A#","B#","C##"),
array("Eb","F","G","Ab","Bb","C","D","Eb","F","G","Ab","Bb","C","D"),
array("E","F#","G#","A","B","C#","D#","E","F#","G#","A","B","C#","D#"),
array("E#","F##","G##","A#","B#","C##","D##","E#","F##","G##","A#","B#","C##","D##"),
array("Fb","Gb","Ab","Bbb","Cb","Db","Eb","Fb","Gb","Ab","Bbb","Cb","Db","Eb"),
array("F","G","A","Bb","C","D","E","F","G","A","Bb","C","D","E"),
array("F#","G#","A#","B","C#","D#","E#","F#","G#","A#","B","C#","D#","E#"),
array("Gb","Ab","Bb","Cb","Db","Eb","F","Gb","Ab","Bb","Cb","Db","Eb","F"),
array("G","A","B","C","D","E","F#","G","A","B","C","D","E","F#"),
array("G#","A#","B#","C#","D#","E#","F##","G#","A#","B#","C#","D#","E#","F##"),
array("Ab","Bb","C","Db","Eb","F","G","Ab","Bb","C","Db","Eb","F","G"),
array("A","B","C#","D","E","F#","G#","A","B","C#","D","E","F#","G#"),
array("A#","B#","C##","D#","E#","F##","G##","A#","B#","C##","D#","E#","F##","G##"),
array("Bb","C","D","Eb","F","G","A","Bb","C","D","Eb","F","G","A"),
array("B","C#","D#","E","F#","G#","A#","B","C#","D#","E","F#","G#","A#"),
array("B#","C##","D##","E#","F##","G##","A##","B#","C##","D##","E#","F##","G##","A##"),
array("Cb","Db","Eb","Fb","Gb","Ab","Bb","Cb","Db","Eb","Fb","Gb","Ab","Bb")
);
$bass is a string, like the one inside the arrays. The $selected_scale is just a number.
What I'm trying to do is to find the $bass in one of those array in the position of $selected_scale. Basically, $bass = $major_scales[$selected_scale]. Therefore I want to create a loop in order to get the elements after that.
But I don't know how to manage in this case the situation. I've looked everything in internet and try various solutions without success. I'd like to know how can I do it. Thanks
Try to use next loop:
// if value exists in mentioned index
if (in_array($bass,$major_scales[$selected_scale])){
// index of that value in that array
$tmp_ind = array_search($bass,$major_scales[$selected_scale]);
// length of the array
$len = count($major_scales[$selected_scale]);
// store values after this value
$res = [];
for ($i=$tmp_ind;$i<$len;$i++){
$res[$i] = $major_scales[$selected_scale][$i];
}
}
print_r($res);
Demo1
If you need to find value by index $selected_scale in one of these arrays and also store values after this position:
foreach($major_scales as $ar){
if ($ar[$selected_scale] == $bass){
// length of the array
$len = count($ar);
// store values after this value
$res = [];
for ($i=$selected_scale;$i<$len;$i++){
$res[$i] = $ar[$i];
}
}
}
print_r($res);
Demo2

How do I create a procedural multi dimensional array with PHP

I'm super new at php, I'm working on a game in Unity c# and I'm trying to send and receive data from a mysql server. I think I'm having a problem with syntax. I basically have a string that's being sent from my c# script that holds multiple ships with their stats. The ships are seperated by zzz which is a string of it's stats separated by space. I'd like to be able to set the stats array within the ships array. This is what I have but it's not working. Thanks!!
$shiparraytobesplit = $_POST["shipinventory"];
$ships = explode("zzz", $shiparraytobesplit);
for($i = 0; $i<count($ships)-1; $i++)
{
$tempship[$i] = $ships[$i];
$tempshipinfo = explode(" ", $tempship);
for($ii = 0; $ii<count($tempshipinfo[!i])-1; $ii++)
{
//$shipinfo[$tempship][] = $info . '_' . $tempshipinfo;
$shipinfo[$ii] = $tempshipinfo[$ii];
}
echo $shipinfo[1];
}
I've tried a few variations but I can't seem to get it to work with this example. I'm probably missing something simple since I'm a total noob to php and kind of new to programming. Thanks again
You have some extraneous subscripts that aren't needed.
If you have an extra element in the array, it's probably easier to just unset it, then you can loop over the entire array. array_map() is an easy way to produce a new array from an existing array.
$shiparraytobesplit = $_POST["shipinventory"];
$ships = explode("zzz", $shiparraytobesplit);
unset($ships[count($ships)-1]);
$shipinfo = array_map(function($ship) {
$tempshipinfo = explode(" ", $ship);
unset($tempshipinfo[count($tempshipinfo)-1]);
return $tempshipinfo;
}, $ships);
print_r($shipinfo);
If you want associative arrays, you can do that in the function.
$shiparraytobesplit = $_POST["shipinventory"];
$ships = explode("zzz", $shiparraytobesplit);
unset($ships[count($ships)-1]);
$shipinfo = array_map(function($ship) {
$tempshipinfo = explode(" ", $ship);
$ship_assoc = [
"id" => $tempshipinfo[0],
"name" => $tempshipinfo[1],
"username" => $tempshipinfo[2],
"hp" => $tempshipinfo[3]
];
return $ship_assoc;
}, $ships);
print_r($shipinfo);

How to get access to class field which is variable

Firstly, look my example json output.
I have next question. I have some fields in json code like 'counter_87' or 'coutner_88' in countersData part. It is a variable. I need to get access to this variable class field.
Ofc, I can write:
foreach($objCounter->countersData as $data)
{
print $data->counter_87;
}
It is working fine. But...
I have counters ID and I need to get access to fields which are named depending on this ID's.
Full code, which will show what I want:
foreach($objCounter->countersData as $data)
{
$row = "<td width=100px>$data->month $data->year</td>";
foreach($objCounter->counters as $counter)
{
$counterId = $counter->id;
$counterValue = "$data->counter_$counterId";
$row .= "<td>$counterValue</td>";
}
$table .= "<tr>$row</tr>";
}
I need same:
$foo = 'bar';
$bar = 'foobar';
echo $$foo; // foobar will be printed
But with classes.
Thank you.
You could also do the following if you don't want to or can't change change your JSON structure as already mentioned in the comments.
$field_name = 'counter_'.$id;
$field_value = $data->$field_name;
$row .= "<td>$field_value</td>";
// or $row .= '<td>'.$data->$field_name.'</td>';
About rewriting the JSON. Here's code that would convert your JSON to the slightly better structure.
$data = json_decode($data_json);
foreach($data->countersData as $counter_data) {
$counters = array();
foreach($counter_data as $key => $val) {
if(substr($key, 0, 8) == 'counter_') {
$counters[substr($key, 8)] = $val;
unset($counter_data->$key);
}
}
$counter_data->counters = $counters;
}
$data_json_new = json_encode($data);
Using an array instead of fields like 'counter_1', 'counter_2' means having structure like this this:
$countersData[0]->counters[90] = 1;
$countersData[0]->counters[89] = 1;
$countersData[0]->counters[88] = 1;
Instead of
$countersData[0]->counters_90 = 1;
$countersData[0]->counters_89 = 1;
$countersData[0]->counters_88 = 1;
This means having an associative array called counters instead of separate fields like 'counter_90' or something. It makes accessing the data programmatically alot easier.
Note that associative array is very similar to the stdClass. Basically a different datatype serving the same purpose. Using an array to represent your data just makes it easier to deal with integer keys. You can use json_decode($data_json, true) to get the data returned as an associative array.

Categories