Programmatically Building an Associative Array - php

I am currently building a questionnaire system which spans over multiple steps (pages). I am using an assoc array which is stored in session to store the submitted answers.
I am having problems getting my head around how I would build this up programmatically.
The array should be as follows
array(STEP => array(ANSWER 1, ANSWER 2, ANSWER 3, etc...));
I have the step as a variable '$step' and the answer array is built up as a separate '$answers' variable.
So basically what I need to be able to build up is the following
array($step => $answers);

$_SESSION["answers"][$step] = array($ANSWER1, $ANSWER2, <other answers>);
It'd be up to you to define $step and the $ANSWERn variables, of course. And properly initializing your session, too.
After the questionnaire, you'd just step through your array to extract all the answers:
foreach($_SESSION["answers"] as $step => $answer) {
// magic happens here
}
(edit: I slightly modified the foreach to give you the $step variable)

$x = array();
$answer = array();
$answer[0]= "A 1";
$answer[1]= "A 2";
$x[$step] = $answer;

Related

Straight to classify the JSON data

There is a sorted list of questions without classification and I want to sort this list of questions. Because the system of the school works like this. I tried to do this, but I could only do this because I had little PHP knowledge.
In the JSON file, the first part is the question, followed by 4 options and the question begins again.
The amount of questions does not change. Always 4.
Currently JSON file:
$jsonData = '["questionText1","option1","option2","option3","option4","questionText2","option1","option2","option3","option4","questionText3","..."]'; // x150 text
My code:
$jsonParse = json_decode($jsonData, true);
foreach ($jsonParse as $json) {
$cikis[] = array('q' => $json[0]);
}
var_dump($cikis);
Goal:
$jsonData = [
{'q':'questionText','o1':'option1','o2':'option2','o3':'option3','o4':'option4'},
{'q':'questionText','o1':'option1','o2':'option2','o3':'option3','o4':'option4'}
]
I looked for a question like this but couldn't find it. What do I have to do to classify the question and question options separately? like the example above.
You can simply use array_chunk to split your source data into chunks of five items, since each grouping always consists of 1 question + 4 options.
$chunks = array_chunk($jsonParse, 5);
This will give you an array of five-item chunks, with each chunk containing the question as the first item [0], and the options as items [1]...[4]. If you want to turn them into associated arrays, you can do that for example using array_map and array_combine:
$namedChunks = array_map(function($chunk) {
return array_combine(['q', 'o1', 'o2', 'o3', 'o4'], $chunk);
}, $chunks);
This will give you an array with named keys, which you can json_encode($namedChunks) for the output you're looking for. (Your example isn't valid JSON, though!)
A foreach loop and a "manual" building of the associated arrays will also work, and probably will be marginally faster. I'm in the habit of using straight-up loops in code where performance adds up (either frequently called, or with massive data), and using the more elegant array_* functions in favor of more explicit and readable code, where raw performance is less consequential.
You can use array_chunk() to split an array into samesized chunks:
<?php
$numberOfElementsPerChunk = 5; // 1 question + 4 options
$jsonData = '["questionText1","option1","option2","option3","option4","questionText2","option1-2","option2-2","option3-2","option4-2","questionText3","option1-3","option2-3","option3-3","option4-3","questionText4","option1-4","option2-4","option3-4","option4-4"]';
$jsonParse = json_decode($jsonData, true);
$chunks = array_chunk($jsonParse, $numberOfElementsPerChunk);
$result = [];
foreach ($chunks as $question) {
$set = [
'q' => $question[0],
'o1' => $question[1],
'o2' => $question[2],
'o3' => $question[3],
'o4' => $question[4],
];
$result[] = $set;
}
print_r(json_encode($result));
Output:
[{"q":"questionText1","o1":"option1","o2":"option2","o3":"option3","o4":"option4"},{"q":"questionText2","o1":"option1-2","o2":"option2-2","o3":"option3-2","o4":"option4-2"},{"q":"questionText3","o1":"option1-3","o2":"option2-3","o3":"option3-3","o4":"option4-3"},{"q":"questionText4","o1":"option1-4","o2":"option2-4","o3":"option3-4","o4":"option4-4"}]

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.

PHP Date merging class / method?

I am doing work where I get data in various formats from various sources. I will end up with something like this:
$dataSource1 = ... ;
$dataSource2 = ... ;
$dataSource3 = ... ;
I need to COMBINE these data sources, all with different field names, into one object, that I can sort according to fields, limit to X number etc.... all for display purposes.
What is the best way to do this? Is there a good php library that does this?
Three possible solutions,
You could always create a database and just use that. (Probably the best thing to do)
Alternatively, you could try attempt to do some polymorphisisng? (cant be made into a verb!)
Finally, you could also include all the other pages into the one you will be displaying from.
(I suggest number 1)
I think the simplest way is using an associative array.
$dataSource1 = ...;
$dataSource2 = ...;
...
$dataSourceN = ...;
$data = array()
$data[0] = $dataSource1;
$data[1] = $dataSource2;
And so on. Just remember that a numeric index array always starts at 0. So the first element would be $data[0].
If you want a more complex bind you can create a multidimensional array. It means you can sort by specific fields. See an example:
$data1 = 'Brazil';
$dataArray = array()
$dataArray[] = array(
'countryId' => 'id',
'countryName' => $data1,
'usersFromThisCountry' => $data1Users
);
Now you can sort $dataArray according to 'countryId','countryName','usersFromThisCountry'.

Autofill array with empty data to match another array size

I have 2 sets of arrays:
$dates1 = array('9/12','9/13','9/14','9/15','9/16','9/17');
$data1 = array('5','3','7','7','22','18');
// for this dataset, the value on 9/12 is 5
$dates2 = array('9/14','9/15');
$data2 = array('12','1');
As you can see the 2nd dataset has fewer dates, so I need to "autofill" the reset of the array to match the largest dataset.
$dates2 = array('9/12','9/13','9/14','9/15','9/16','9/17');
$data2 = array('','','12','1','','');
There will be more than 2 datasets, so I would have to find the largest dataset, and run a function for each smaller dataset to properly format it.
The function I'd create is the problem for me. Not even sure where to start at this point. Also, I can format the date and data arrays differently (multidimensional arrays?) if for some reason that is better.
You can do this in a pretty straightforward manner using some array functions. Try something like this:
//make an empty array matching your maximum-sized data set
$empty = array_fill_keys($dates1,'');
//for each array you wish to pad, do this:
//make key/value array
$new = array_combine($dates2,$data2);
//merge, overwriting empty keys with data values
$new = array_merge($empty,$new);
//if you want just the data values again
$data2 = array_values($new);
print_r($data2);
It would be pretty easy to turn that into a function or put it into a for loop to operate on your array sets. Turning them into associative arrays of key/value pairs would make them easier to work with too I would think.
If datas are related will be painful to scatter them on several array.
The best solution would be model an object with obvious property names
and use it with related accessor.
From your question I haven't a lot of hint of what data are and then I have to guess a bit:
I pretend you need to keep a daily log on access on a website with downloads. Instead of using dates/data1/data2 array I would model a data structure similar to this:
$log = array(
array('date'=>'2011-09-12','accessCount'=>7,'downloadCount'=>3),
array('date'=>'2011-09-13','accessCount'=>9), /* better downloadsCount=>0 though */
array('date'=>'2011-09-15','accessCount'=>7,'downloadCount'=>3)
...
)
Using this data structure I would model a dayCollection class with methods add,remove,get,set, search with all methods returning a day instance (yes, the remove too) and according signature. The day Class would have the standard getter/setter for every property (you can resolve to magic methods).
Depending on the amount of data you have to manipulate you can opt to maintain into the collection just the object data (serialize on store/unserialize on retrieve) or the whole object.
It is difficult to show you some code as the question is lacking of details on your data model.
If you still want to pad your array than this code would be a good start:
$temp = array($dates, $data1, $data2);
$max = max(array_map('count',$temp));
$result = array_map( function($x) use($max) {
return array_pad($x,$max,0);
}, $temp);
in $result you have your padded arrays. if you want to substitute your arrays do a simple
list($dates, $data1, $data2) = array_map(....
You should use hashmaps instead of arrays to associate each date to a data.
Then, find the largest one, cycle through its keys with a foreach, and test the existence of the same key in the small one.
If it doesn't exist, create it with an empty value.
EDIT with code (for completeness, other answers seem definitely better):
$dates_data1 = array('9/12'=>'5', '9/13'=>'3', '9/14'=>'7' /* continued */);
$dates_data2 = array('9/14'=>'12', '9/15'=>'1');
#cycle through each key (date) of the longest array
foreach($dates_data1 as $key => $value){
#check if the key exists in the smallest and add '' value if it does not
if(!isset( $date_data2[$key] )){ $date_data2[$key]=''; }
}

Duplicate array but maintain pointer links

Suppose I have an array of nodes (objects). I need to create a duplicate of this array that I can modify without affecting the source array. But changing the nodes will affect the source nodes. Basically maintaining pointers to the objects instead of duplicating their values.
// node(x, y)
$array[0] = new node(15, 10);
$array[1] = new node(30, -10);
$array[2] = new node(-2, 49);
// Some sort of copy system
$array2 = $array;
// Just to show modification to the array doesn't affect the source array
array_pop($array2);
if (count($array) == count($array2))
echo "Fail";
// Changing the node value should affect the source array
$array2[0]->x = 30;
if ($array2[0]->x == $array[0]->x)
echo "Goal";
What would be the best way to do this?
If you use PHP 5:
Have you run your code? It is already working, no need to change anything. I get:
Goal
when I run it.
Most likely this is because the values of $array are already references.
Read also this question. Although he OP wanted to achieve the opposite, it could be helpful to understand how array copying works in PHP.
Update:
This behaviour, when copying arrays with objects, the reference to the object is copied instead the object itself, was reported as a bug. But no new information on this yet.
If you use PHP 4:
(Why do you still use it?)
You have to do something like:
$array2 = array();
for($i = 0; $i<count($array); $i++) {
$array2[$i] = &$array[$i];
}
it is some time that I don' write PHP code, but does the code
// Some sort of copy system
$array2 = $array;
actually work?
Don't you have to copy each element of the array in a new one?

Categories