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;
}
}
Related
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 ->.
I will be getting some certain amount of data. I will get the number for which the for loop to be run.
For example
I get the number 3 and I will get three parameters like par1,par2 and par3 then how should I pass this par1 in the $_post
like
$i=$_POST["number"];
for($i=1;$i<=$n;$i++)
{
$par.$i = $_POST["par".$i];
}
Here I cant get the value from $_POST["par".$i];
As it is not able to get the variable inside the paramater of $_POST
Any help will be thankful
I suggest that you create a new array $par and there you will put by index all the par you will have like this:
$i=$_POST["number"];
$par = [];
for($i=1;$i<=$n;$i++)
{
$par[$i] = $_POST["par".$i];
}
After that if you want to go throw all pars you can simply use foreach like this:
foreach($par as $key => $value) {
// $key will be 1,2,3
// $value will be the value from $_POST["par" . $i]
}
The . is to concatenate two strings in PHP, and you can't create a new variable like you tried. If you want to have in $par1, $par2 and $par3 you can do like this:
${"par" . $i} = $_POST["par".$i];
But I don't recommend this way because it's more hard to handle.
One Way
According to your question.
<?php
$n = $_POST["number"];
$par = "par";
for($i=1; $i<=$n; $i++){
$par.$i = $_POST["par".$i];
}?>
Alternative Way
In this scenario,
For example I get the number 3 and I will get three parameters like
par1,par2 and par3 then how should I pass this par1 in the $_post.
Better, make 'par' input name as an array type as 'par[]' (<input type='text' name='par[]'>) in your file instead using par1, par2 .. par(n).
And, no need to worry in submit page.
<?php
$n = $_POST["number"];
for($i=1;$i<= $n;$i++){
$newPar = $_POST["par"][$i];
// Write here your logic to use how you want.
}
?>
I'm becoming a little frustrated with my array results. Ideally, I am creating a form maker module within my application and I am working with two different arrays to establish my database columns and excel columns. Essentially, I am using the results provided by the arrays to write directly to a php file (Excel reader file). In order to establish a difference in Excel Workbooks, I am putting forth an identifier "page2","page3" and so on within the "excel_rows" array.
//my arrays
$table_columns = array('field1','field2','field3','field4','field5'); //fields
$excel_rows = array('c1','c2','page2','c3','c4','page3','c5'); //excel columns
From here.. I go on to try to filter the array keys..
foreach(array_keys($excel_rows) as $key){
$page = array_search(strpos(trim($excel_rows[$key]),'page'),$excel_rows);
if(strpos(trim($excel_rows[$key]),'page') !== false){
$excel_row .= '$objTpl->setActiveSheetIndex('.(str_replace('page','',trim($excel_rows[$key])) -1).');<br/>'.PHP_EOL;
$table_columns[$key] = 0;
}
else {
$excel_row .= '$objTpl->getActiveSheet()->setCellValue(\''.trim($excel_rows[$key]).'\',$row[\''.trim($table_columns[$key]).'\']);<br/>'.PHP_EOL;
}
}
print $excel_row;
The result should echo out the following:
$objTpl->getActiveSheet()->setCellValue('c1', $row['field1']);
$objTpl->getActiveSheet()->setCellValue('c2', $row['field2']);
$objTpl->setActiveSheetIndex(1);<br/>
$objTpl->getActiveSheet()->setCellValue('c3', $row['field4']);
$objTpl->getActiveSheet()->setCellValue('c4', $row['field5']);
$objTpl->setActiveSheetIndex(2);
$objTpl->getActiveSheet()->setCellValue('c5', $row['']);
As one can see, I am missing 'field3' from my result and 'cs' produces and empty row rather than "field5".
I'm assuming something like array_compare or array_combine is the solution - I'm just not able to put it together.
Everything works lovely with module pardoning the array code above. Any help with this would be sincerely appreciated!
-Regards.
How it currently is I'd say you need to set an integer +1 whenever you create a new page and then subtract that integer from the key so you can get the right field.
$subkey = 0;
foreach(array_keys($excel_rows) as $key){
$fieldkey = $key - $subkey;
$page = array_search(strpos(trim($excel_rows[$key]),'page'),$excel_rows);
if(strpos(trim($excel_rows[$key]),'page') !== false){
$excel_row .= '$objTpl->setActiveSheetIndex('.(str_replace('page','',trim($excel_rows[$key])) -1).');<br/>'.PHP_EOL;
//$table_columns[$key] = 0; I'm not sure what this is supposed to do
$subkey++;
}
else {
$excel_row .= '$objTpl->getActiveSheet()->setCellValue(\''.trim($excel_rows[$key]).'\',$row[\''.trim($table_columns[$fieldkey]).'\']);<br/>'.PHP_EOL;
}
}
print $excel_row;
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.
Is there a better/shorter way to do this?
Each variable is a MySQL table value that is called. I have a main table and an override table, so call the first table, extract the resulting array, then call the override table and extract those results to override the first extract.
if (isset($Price1)){
$AllPrices[] = $Price1;}
if (isset($Price2)){
$AllPrices[] = $Price2;}
if (isset($Price3)){
$AllPrices[] = $Price3;}
if (isset($Price4)){
$AllPrices[] = $Price4;}
if (isset($SPrice1)){
$AllPrices[] = $SPrice1;}
if (isset($SPrice2)){
$AllPrices[] = $SPrice2;}
if (isset($SPrice3)){
$AllPrices[] = $SPrice3;}
I've done things like this in the past, but I wouldn't recommend it:
$variables = array("Price1", "Price2", "Price3", "Price4", "SPrice1", "SPrice2", "SPrice3");
$AllPrices = array();
foreach ($variables as $variable)
{
if (isset($$variable))
$AllPrices[] = $$variable;
}
See here for more information on how the $$ syntax works in PHP.
But I do agree with the comments to your post... You really should take another look at how you're getting this data. This solution is not ideal in the least.
You can also do like this:
for($i = 1; $i < 4; $i++){
$current = ${'AllPrices'.$i};
isset($current) && array_push($AllPrices, $current);
}
As also posted in above answer, using array of variable names is more efficient.
This structure is not recommended.
Instead of using $price1, $price2, ... use an array - $price[1], $price[2], ... (Do the same for $SPrice).
Then you could use a simple array_merge:
$AllPrices = array_merge($price, $SPrice);