Add new member to a variable in an array - php

I want to append new member to element which is in an array. Without array it's simple to write. for example:
$exp["app_form_id"] = $form_id;
But when I want add new member 'app_form_id' to all object of an array it not insert them and also there's not any error with them. I tried do it by 2 way, but none of them not worked:
1)
foreach ($exps as $exp) {
$exp["app_form_id"] = $form_id;
}
2)
for ($i = 0; $i < count($exps); $i++) {
$exps[i]["app_form_id"] = $form_id;
}

Your #1 method will work if you pass by reference (&):
foreach ($exps as &$exp) {
$exp["app_form_id"] = $form_id;
}

Try like this,
foreach ($exps as &$exp) {
$exp->app_form_id = $form_id;
}
I feel you are having manipulation with an object.
Give it a try, it should work.

Whatever you are changing inside block is limited to the block and not changing back, Try like this
$newExps = array();
foreach ($exps as $exp) {
$exp["app_form_id"] = $form_id;
$newExps[] = $exp;
}
print_r($newExps);

Related

How to declare an array of objects for a for loop in PHP?

I want to insert the details of a quiz in which among a lot of strings (question, professor, course, etc) , I have one array of answers (and its corresponding array of is_correct), so I thought of creating a for loop to insert each answer properly.
The problem is I don't know how to correctly call the questionQuiz object. I noticed if I declare two different objects at the beginning and then do this manually:
$questionQuiz1 -> insert_question($quiz_name,$professor,$course,$question,$points,$answer[0],$is_correct[0]);
$questionQuiz2-> insert_question($quiz_name,$professor,$course,$question,$points,$answer[1],$is_correct[1]);
it works.
How should I declare this object as an array and use it in an iteration?
I tried something like this but it isn't correct.
$questionQuiz[] = new Test();
if(isset($_POST['quiz_name'],$_POST['professor'],$_POST['course'],$_POST['question'],$_POST['points'],$_POST['answer'], $_POST['is_correct'])) {
$quiz_name = $_POST['quiz_name'];
$professor = $_POST['professor'];
$course = $_POST['course'];
$question = $_POST['question'];
$points = $_POST['points'];
$answer = $_POST['answer'];
$is_correct = $_POST['is_correct'];
if(!empty($quiz_name) && !empty($professor)&& !empty($course)&& !empty($question)&& !empty($points)&& !empty($answer) && !empty($is_correct)){
for($i=0; $i<count($answer); $i++) {
$questionQuiz[$i] -> insert_question($quiz_name,$professor,$course,$question,$points,$answer[$i],$is_correct[$i]);
}
}else{
echo json_encode("param must not be empty");
}
}
Should I instantiate $questionQuiz[] = new Test(); inside the loop? I tested and it seems to work, is it correct to do it this way?
So the problem in your code, is that you only create 1 instance of Test class (at the top). And inside your for loop, you only reference it and call the insert_question method on it. Beware: in this case only $questionQuiz[0] exists, so in the other cases nothing happens (or an error might occur).
Option 1
If you only want to call the method on the Test class, you could call it in your for loop like this:
(new Test())->insert_question( ... etc ... );
Option 2
If you want to store the created class objects, you create a new Test object, call the insert_question method on it and add the object to your array:
$object = new Test();
$object->insert_question( ... etc ...);
$questionQuiz[] = $object;
You seem to have the logic all laid out, your just not doing what you're saying.
Create an array, and then add a new object to that array each time through the loop.
$questionQuiz[] = array();
if(isset($_POST['quiz_name'],$_POST['professor'],$_POST['course'],$_POST['question'],$_POST['points'],$_POST['answer'], $_POST['is_correct'])) {
...
for($i=0; $i<count($answer); $i++) {
$questionQuiz[$i] = new Test();
$questionQuiz[$i] -> insert_question($quiz_name,$professor,$course,$question,$points,$answer[$i],$is_correct[$i]);
}
...
I will note however, that something seems off about having a function called insert_question() where you individually insert single answers options on seemingly multiple-choice questions. I would think you would pass an array of answer options with corresponding correctness.
You mentioned storing the posts to an object array. would something like this work?
<?php
if(isset($_POST['quiz_name'], $_POST['professor'], $_POST['course'], $_POST['question'], $_POST['points'], $_POST['answer'], $_POST['is_correct']))
{
$quiz_name = $_POST['quiz_name'];
$professor = $_POST['professor'];
$course = $_POST['course'];
$question = $_POST['question'];
$points = $_POST['points'];
$answer = $_POST['answer'];
$is_correct = $_POST['is_correct'];
}
if(!empty($answer_array) && count($answer_array[5]) > 0)
{
$count = count($answer_array[5]);
$questionQuiz[] = new Test();
for($i=0; $i < $count; $i++)
{
//assuming your class is correct and you'll need to have it handle the incoming array how you want it to
$answer_array = array($quiz_name, $professor, $course, $question, $points, $answer[$i], $is_correct[$i]);
$questionQuiz[$i] -> insert_question($answer_array);
}
}
else
{
echo "param must not be empty";
}
?>

Ensure order in for loop involving json_decode()

I'm using json_decode to parse JSON files. In a for loop, I attempt to capture specific cases in the JSON in which one element or another exist. I've implemented a function that seems to fit my needs, but I find that I need to use two for loops to get it to catch both of my cases.
I would rather use a single loop, if that's possible, but I'm stuck on how to get both cases caught in a single pass. Here's a mockup of what I would like the result to look like:
<?php
function extract($thisfile){
$test = implode("", file($thisfile));
$obj = json_decode($test, true);
for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) {
//this is sometimes found 2nd
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring1") {
}
//this is sometimes found 1st
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring2") {
}
}
}
?>
Can anyone tell me how I could catch both cases outlined above within a single iteration?
I clearly could not do something like
if ($obj['patcher']['boxes'][$i]['box']['name'] == "string1" && $obj['patcher']['boxes'][$i]['box']['name'] == "string2") {}
...because that condition would never be met.
Generally what I do when I have raw data that is in an order that isn't ideal to work with is to run a first loop pass to generate a a list of indexes for me to pass through a second time.
So a quick example from your code:
<?php
function extract($thisfile){
$test = implode("", file($thisfile));
$obj = json_decode($test, true);
$index_mystring2 = array(); //Your list of indexes for the second condition
//1st loop.
$box_name;
for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) {
$box_name = $obj['patcher']['boxes'][$i]['box']['name'];
if ( $box_name == "mystring1") {
//Do your code here for condition 1
}
if ($box_name == "mystring2") {
//We push the index onto an array for a later loop.
array_push($index_mystring2, $i);
}
}
//2nd loop
for($j=0; $j<=sizeof($index_mystring2); $j++) {
//Your code here. do note that $obj['patcher']['boxes'][$j]
// will refer you to the data in your decoded json tree
}
}
?>
Granted you can do this in more generic ways so it's cleaner (ie, generate both the first and second conditions into indexes) but i think you get the idea :)
I found that something like what #Jon had mentioned is probably the best way to attack this problem, for me at least:
<?php
function extract($thisfile){
$test = implode("", file($thisfile));
$obj = json_decode($test, true);
$found1 = $found2 = false;
for ($i = 0; $i <= sizeof($obj['patcher']['boxes']); $i ++) {
//this is sometimes found 2nd
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring1") {
$found1 = true;
}
//this is sometimes found 1st
if ($obj['patcher']['boxes'][$i]['box']['name'] == "mystring2") {
$found2 = true;
}
if ($found1 && $found2){
break;
}
}
}
?>

Using arrays in classes PHP

I'm experimenting with classes and objects for the first time and I thought I'd make a template for a Box that can store things like Books. (Thinking in terms of real-world items)
<?php
function feetToInches($feet){
$feet = $feet * 12;
return $feet;
}
class Book{
var $l = 6;
var $w = 5;
var $h = 1;
}
class Box{
//This is a box. It has length, width, and height, and you can put things in it.
var $length = 0;
var $width = 0;
var $height = 0;
var $storedArray = array();
function setDimensions($l, $w, $h){
$this->length = feetToInches($l);
$this->width = feetToInches($w);
$this->height = feetToInches($h);
}
function storeThings($thing){
$this->storedArray[] = $thing;
}
function getThings(){
return $this->storedArray;
}
}
$thatBook = new Book;
$BookBox = new Box;
$BookBox->setDimensions(6,5,1);
for($i = 0; $i < 5; $i++){
$BookBox->storeThings($thatBook);
}
echo $BookBox->getThings() . "<br />";
/*
foreach($BookBox->getThings() as $item){
echo $item;
}
*/
var_dump($BookBox);
?>
So what I have is simple here, you have boxes of a dimension, and you throw books of a fixed dimension in them.
Putting things in it is no problem, but when I try to retrieve them, I either get errors or nothing happens. And when I try to specify a key for the array like
echo $BookBox->getThings()[2];
I get an error that it's not an array or something.
So can someone please point me in the right direction here?
And normally the class would be a separate file, but I'm just learning here.
What version of PHP are you using.
Array dereferencing (referencing into a returned array) was only added in PHP 5.4.
If you're using a previous version, you'd have to do this:
$books = $BookBox->getThings();
echo $books[2];
Edit
Since you are pushing Books into a box, $books[2] returns you an instance of the Book object. Echo is used to output a string, hence the error.
You can either echo a particular property of the book, or print out all of the properties by doing:
print_r($books[2]);
First, you cannot do echo since what you'll get is not a string but an object. Use print_r() or var_dump() instead.
Second, just like the other answers here, you should do this.
$books = $BookBox->getThings();
print_r($books[2]);
But I suggest you to make getThings() accept a variable for getting a specified array element:
function getThings($key = null) {
if ($key) {
return isset($this->storedArray[$key]) ? $this->storedArray[$key] : null;
} else {
return $this->storedArray;
}
}
// Then you can do this
// print_r($BookBox->getThings(2));
What you are calling when you call $BookBox->getThings() is actually an object and not an array.
You might try something along the lines of:
$books = $BookBox->GetThings();
echo $books[2];

convert array to object in php

In php I am converting posted data from a form to objects like this:
<?php
...some code...
$post = new stdClass;
foreach ($_POST as $key => $val)
$post->$key = trim(strip_tags($_POST[$key]));
?>
Then in my page I just echo posted data like this :
<?php echo $post->Name; ?>
<?php echo $post->Address; ?>
etc...
This works fine but I have multiple checkboxes that are part of a group and I echo the results of that, like this:
<?php
$colors = $_POST['color_type'];
if(empty($colors))
{
echo("No color Type Selected.");
}
else
{
$N = count($colors);
for($i=0; $i < $N; $i++)
{
echo($colors[$i] . ", ");
}
}
?>
That works when I am just using array, but how do I write this as object syntax?
using your code
function array_to_object($arr) {
$post = new stdClass;
foreach ($arr as $key => $val) {
if(is_array($val)) {
$post->$key = post_object($val);
}else{
$post->$key = trim(strip_tags($arr[$key]));
}
}
return $post;
}
$post = array_to_object($_POST);
or more complex solution
function arrayToObject($array) {
if(!is_array($array)) {
return $array;
}
$object = new stdClass();
if (is_array($array) && count($array) > 0) {
foreach ($array as $name=>$value) {
$name = strtolower(trim($name));
if (!empty($name)) {
$object->$name = arrayToObject($value);
}
}
return $object;
}
else {
return FALSE;
}
}
from http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass
why would you want that? What's wrong with an array?
Use Object Oriented Programming, which might be what you are looking for. Treat it as an object, by making a class called Color and doing $colors[$i] = new Color();
This way you can do whatever you want with it, and add functions to it.
Pretty simple -- when you attach the color_type key to your object, it'll become an array that's a property of your object. This is most likely what you want: you probably won't want to turn that array into its own stdClass-based object, because then you won't be able to iterate through all the values (as easily). Here's a snippet:
<?php
// putting in both of these checks prevents you from throwing an E_WARNING
// for a non-existent property. E_WARNINGs aren't dangerous, but it makes
// your error messages cleaner when you don't have to wade through a bunch
// of E_WARNINGS.
if (!isset($post->color_type) || empty($post->color_type)) {
echo 'No colour type selected.'; // apologies for the Canadian spelling!
} else {
// this loop does exactly the same thing as your loop, but it makes it a
// bit more succinct -- you don't have to store the count of array values
// in $N. Bit of syntax that speeds things up!
foreach ($post->color_type as $thisColor) {
echo $thisColor;
}
}
?>
Hope this helps! Of course, in a real-life setting, you'll want to do all sorts of data validation and cleaning -- for instance, you'll want to check that the browser actually passed an array of values for $_POST['color_type'], and you'll want to clean the output in case someone is trying to inject an exploit into your page (by going echo htmlspecialchars($thisColor); -- this turns all characters like < and > into HTML entities so they can't insert JavaScript code).

Output a result of an SQL query to a PHP array

I'm new to OOP in PHP, is that to seems correct ?
class whatever {
Function Maths() {
$this->sql->query($requete);
$i = 0;
while($val = mysql_fetch_array($this)) {
$tab[i][average] = $val['average'];
$tab[i][randomData] = $val['sum'];
$i=$i+1;
}
return $tab;
}
I want to access the data contained in the array
$foo = new whatever();
$foo->Maths();
for ($i, $i <= endOfTheArray; i++) {
echo Maths->tab[i][average];
echo Maths->tab[i][randomData];
}
Thank you ;)
EDIT: i want to output the result of the SQL query as an array, so i can access it from outside the class
In the interest of helping you out, here are some modifications. Please hear this, though: a lot of this might not make sense without a good background in PHP or OOP in general. You should look at #webbiedave's link.
class whatever {
static function maths() {
$tabs = array();
$results = $this->sql->query($requete);
while($val = mysql_fetch_array($this)) {
$tabs = $val;
}
return $tabs;
}
This fixes syntax errors and logic errors (for instance, the creation of the $results variable to hold the SQL query run).
I made the maths method static, since there's really no need to instantiate a whatever() object with this current example.
Here are some modifications to how this would be used:
$results = whatever::maths();
foreacho ($results as $result) {
echo $result['average'];
echo $result['randomData'];
}
Since maths() returns something, you need to store that in a variable; simply calling it, as you did previously, doesn't do anything.
That convoluted for loop can be replaced with a foreach loop.
Please check out PHP OOP basics:
http://www.php.net/manual/en/language.oop5.basic.php
Edit: Thanks for cleaning up the code. Try something along the lines of:
$tabs = array();
while($val = mysql_fetch_assoc($result)) {
$tabs[] = $val;
}
And:
$foo = new whatever();
$tabs = $foo->Maths();
for ($tabs as $tab) {
echo $tab['average'];
echo $tab['randomData'];
}
http://www.php.net/manual/en/language.oop5.basic.php

Categories