store objects in an array during foreach? - php

I am looking to store some objects in an array during a foreach loop. The problem is creating a unique object each time. I have to have some kind of index appending the name of each object. Here is what I have:
function table_rows($html) {
$dom = new Zend_Dom_Query($html);
$table_rows = $dom->query('tr');
$check_array = array();
foreach ($table_rows as $key=>$table_row) {
($check_object . $key) = new check_class;
($check_object . $key)->check_method1($table_row);
($check_object . $key)->check_method2($table_row);
($check_object . $key)->check_method3($table_row);
$check_array[] = (check_object . $key);
}
}
Am I even close?

You could use variables for that:
function table_rows($html) {
$dom = new Zend_Dom_Query($html);
$table_rows = $dom->query('tr');
$check_array = array();
foreach ($table_rows as $key=>$table_row) {
$object = new check_class;
$object->check_method1($table_row);
$object->check_method2($table_row);
$object->check_method3($table_row);
$check_array[] = $object;
}
}
Of course naming the variable for an object instance $object is not very descriptive, but I hope you get the idea.
This works because the first assignment in the for-loop overwrites the "old" instance, so $object unique for each iteration.

In case Jared Drake is right and what you mean is unique array keys, not object (variable) names.
$dom = new Zend_Dom_Query($html);
$table_rows = $dom->query('tr');
$check_array = array();
foreach ($table_rows as $key=>$table_row) {
$check_object = new check_class;
$check_object->check_method1($table_row);
$check_object->check_method2($table_row);
$check_object->check_method3($table_row);
$check_array['check_object' . $key] = $check_object;
}
}

Maybe I'm misunderstanding the question, but can't you just use the array_push method to add each object to the end of the array in your foreach loop?

Related

PHP Removing by reference

I'm trying to remove stdClass property by reference. Because I don't know how deeply the property is nested, a reference is made in the loop. But the unset method does not remove variables by reference. How can I resolve it without just setting a null value?
<?php
$data = new stdClass();
$data->foo = new stdClass();
$data->foo->bar = 'value';
$pathToRemove = 'foo.bar';
$dataReference = &$data;
foreach (explode('.', $pathToRemove) as $field) {
$dataReference = &$dataReference->$field;
}
unset($dataReference);
var_dump($data);
Loop over all the elements except the last. Then use the last element as the field to delete.
$pathArray = explode('.', $pathToRemove);
$lastField = array_pop($pathArray);
$dataReference = &$data;
foreach ($pathArray as $field) {
$dataReference = &$dataReference->{$field};
}
unset($dataReference->{$lastField});
unset($dataReference); // don't need the reference variable any more

How to trim object properties in PHP?

I have an object $obj as
$obj->{' Property1'} = " value1";
$obj->{'Property2 '} = "value2 ";
I want to get this object $obj as
$obj->{'Property1'} = "value1";
$obj->{'Property2'} = "value2";
I am able to trim all the values using
foreach($obj as $prop => &$val)
{
$val = trim($val);
}
but doing this (below) causing an error
foreach($obj as &$prop => &$val)
{
$prop = trim($prop);
$val = trim($val);
}
Please tell a solution.
Thanks in advance.
You can't reference a key.
What you have to do is unset it, and set the trimmed version like this:
<?php
$obj = new stdClass;
$obj->{' Property1'} = " value1";
foreach($obj as $prop => $val)
{
unset($obj->{$prop});
$obj->{trim($prop)} = trim($val);
}
var_dump($obj);
A little comment to Daan's answer. In his case script will fall into infinite loop if $obj have more than one property. So a working code looks like this.
<?php
$obj = new stdClass;
$obj->{' Property1'} = " value1";
$obj->{'Property2 '} = "value2 ";
$newObj = new stdClass;
foreach($obj as $prop => $val)
{
$newObj->{trim($prop)} = trim($val);
}
$obj = $newObj;
unset($newObj);
var_dump($obj);
Because you're trying to trim the property of the object. You can't do that.
That would work for an array, but not for an object. If you need to alter the properties of an object you need to change the properties of the class.

how to check Foreach loop is working

Im very new to PHP coding.
Just im getting values from object (class Project)and im iterating all object items to calculate duration of each project.
$projectDet = new Project();
$projectList = $projectDet->Find("name = ?",array($requ['name'] ));
if($projectList==false)
return 0;
foreach($projectList as $proj)
{
$reportData = array();
$reportData[] = array("Project","TotalTime"); //Testing
$key = $proj->id;
$EstDUR[$key] = (strtotime($proj->Enddt) - strtotime($proj->Startdt));
}
return $reportData;
But reportData returns null even projectList is not null.
Initate $reportData before foreach:
$reportData = array()
foreach($projectList as $proj) {
(..)

PHP foreach Loop Element Index

I have an XPath query that gets Genres of a movie.
$genreXpath = $xml_data->xpath("//category");
I get the attributes from $genreXpath like this
$genreName=array();
$genresID=array();
$i=0;
foreach($genreXpath as $node) {
$genre = $node->attributes();
$genreName[$i] = $node["name"];
$genresID[$i] = $node["id"];
$i++;
}
I'm going to be writing these values to a Db hence the two different arrays.
This code works but I know there has to be a better way of doing this be it with a 2 d array, not using a $i counter or something more obvious that I haven't figured out....any pointers???
foreach($genreXpath as $i=>$node) { //note $i is your index of the current $node
$genre = $node->attributes();
$genreName[$i] = $node["name"];
$genresID[$i] = $node["id"];
}
It auto increments and you do not need to declare it above.
Use foreach($genreXpath as $key => $node) {
If you looking to a multidimensional you could do:
$genres = array();
foreach($genreXpath as $node) {
$genre = $node->attributes();
$genres[] = array($node["name"], $node["id"]);
}

php simplexml - string as object

Hoping somebody can advise on an issue I have with simplexml.
I need to specify the paths for various nodes but I'm not sure if this is possible.
$xml = new SimpleXMLElement($xmlstr);
$image1 = 'images->image[0]->image';
foreach ($xml->record as $record) {
echo $record->$image1; // i need this be be recognised as $record->images->image[0]->image
}
Hope this makes sense! Thanks
You can use an array for this:
$xml = new SimpleXMLElement($xmlstr);
$levels = array('images', array('key' => 'image', 'index' => 0), 'image');
foreach ($xml->record as $record) {
$obj = $record;
foreach($levels as $level) {
if(is_array($level))
$obj = $obj->{$level['key']}[$level['index']];
else
$obj = $obj->$level;
}
echo $obj;
}
This builds up the hierarchy by reassigning $obj equal to itself -> whatever is next in the array.
PHP cannot interpolate array indices in strings, so if you need to use them, just use an associate array as shown above. :-)

Categories