PHP object operator building string within foreach? - php

I am trying to build an object that will hold multiple objects based of iterating through an array:
<?php
$final_object = new stdClass();
$array = ['one','two'];
$temp_str = '';
foreach ($array as $value) {
$temp_str .= $value . '->';
}
$temp_str = rtrim($temp_str, '->');
$final_object->$temp_str = 999;
print_r($final_object);
exit;
As you can guess, the parser treats '->' as a string literal and not a PHP object operator.
Is what I am attempting to do possible?
Eventually, I want to build a json string after json_encoding to: {"one":{"two": 999}}

You could store a reference of the object during the loop and assign your value at the end:
$final_object = new stdClass();
$array = ['one','two'];
$ref = $final_object ;
foreach ($array as $value) {
$ref->$value = new stdClass() ;
$ref = &$ref->$value ; // keep reference of last object
}
$ref = 999; // change last reference to your value
print_r($final_object);
Outputs:
stdClass Object
(
[one] => stdClass Object
(
[two] => 999
)
)
You could do the same using arrays:
$array = ['one','two'];
$final_object = [];
$ref =& $final_object;
foreach ($array as $value) {
$ref[$value] = [];
$ref =& $ref[$value];
}
$ref=999;
echo json_encode($final_object);
Outputs:
{"one":{"two":999}}

Related

PHP: Set object properties inside a foreach loop

Is it possible to set property values of an object using a foreach loop?
I mean something equivalent to:
foreach($array as $key=>$value) {
$array[$key] = get_new_value();
}
EDIT: My example code did nothing, as #YonatanNir and #gandra404 pointed out, so I changed it a little bit so it reflects what I meant
You can loop on an array containing properties names and values to set.
For instance, an object which has properties "$var1", "$var2", and "$var3", you can set them this way :
$propertiesToSet = array("var1" => "test value 1",
"var2" => "test value 2",
"var3" => "test value 3");
$myObject = new MyClass();
foreach($propertiesToSet as $property => $value) {
// same as $myObject->var1 = "test value 1";
$myObject->$property = $value;
}
Would this example help at all?
$object = new stdClass;
$object->prop1 = 1;
$object->prop2 = 2;
foreach ($object as $prop=>$value) {
$object->$prop = $object->$prop +1;
}
print_r($object);
This should output:
stdClass Object
(
[prop1] => 2
[prop2] => 3
)
Also, you can do
$object = new stdClass;
$object->prop1 = 1;
$object->prop2 = 2;
foreach ($object as $prop=>&$value) {
$value = $value + 1;
}
print_r($object);
You can implement Iterator interface and loop through the array of objects:
foreach ($objects as $object) {
$object->your_property = get_new_value();
}
Hacked away at this for a few hours and this is what i finally used. Note the parameters passed by reference in two places. One when you enter the method and the other in the foreach loop.
private function encryptIdsFromData(&$data){
if($data == null)
return;
foreach($data as &$item){
if(isset($item["id"]))
$item["id"] = $this->encrypt($item["id"]);
if(is_array($item))
$this->encryptIdsFromData($item);
}
}

PHP Rename object property while maintaining its position

How can I rename an object property without changing the order?
Example object:
$obj = new stdClass();
$obj->k1 = 'k1';
$obj->k2 = 'k2';
$obj->k3 = 'k3';
$obj->k4 = 'k4';
Example rename by creating new property:
$obj->replace = $obj->k3;
unset($obj->k3);
Result:
( k1=>k1, k2=>k2, k4=>k4, replace=>k3 )
See the problem?
Simply recreating the object property causes the order to change.
I had a similar issue with arrays and came up with this solution:
Implemented solution for arrays
function replaceKey(&$array, $find, $replace)
{
if(array_key_exists($find, $array)){
$keys = array_keys($array);
$i = 0;
$index = false;
foreach($array as $k => $v){
if($find === $k){
$index = $i;
break;
}
$i++;
}
if ($index !== false) {
$keys[$i] = $replace;
$array = array_combine($keys, $array);
}
}
}
Looking for something similar to this but a function that will work on objects.
Can't seem to find any documentation on object property position indexes.
So, readd your properties
$obj = new YourClass();
$backup = [];
foreach ($obj as $key => $value)
{
$backup[$key] = $value;
unset($obj->$key);
}
replaceKey($backup, $find, $replace);
foreach ($backup as $key => $value)
{
$obj->$key = $value;
}
Since you have a function for your arrays, why dont you do something like :
$array = (array) $obj;
$replacedKeyArray = replaceKey($array);
$newObject = (object) $replacedKeyArray;

Increasing array elements while in foreach loop in php? [duplicate]

This question already has answers here:
How does PHP 'foreach' actually work?
(7 answers)
Closed 8 years ago.
Consider the code below:
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
?>
It is not displaying 'a'. How foreach works with hash-table(array), to traverse each element. If lists are implement why can't I add more at run time ?
Please don't tell me that I could do this task with numeric based index with help of counting.
Foreach copies structure of array before looping(read more), so you cannot change structure of array and wait for new elements inside loop. You could use while instead of foreach.
$arr = array();
$arr['b'] = 'book';
reset($arr);
while ($val = current($arr))
{
print "key=".key($arr).PHP_EOL;
if (!isset($arr['a']))
$arr['a'] = 'apple';
next($arr);
}
Or use ArrayIterator with foreach, because ArrayIterator is not an array.
$arr = array();
$arr['b'] = 'book';
$array_iterator = new ArrayIterator($arr);
foreach($array_iterator as $key=>$val) {
print "key=>$key\n";
if(!isset($array_iterator['a']))
$array_iterator['a'] = 'apple';
}
I think you need to store array element continue sly
Try
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'][] = 'apple';
}
print_r($arr);
?>
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
http://cz2.php.net/manual/en/control-structures.foreach.php
Try this:
You will get values.
<?php
$arr = array();
$arr['b'] = 'book';
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}
echo '<pre>';
print_r($arr);
?>
Output:
key=>b
<pre>Array
(
[b] => book
[a] => apple
)
If you want to check key exist or not in array use array_key_exists function
Eg:
<?php
$arr = array();
$arr['b'] = 'book';
print_r($arr); // prints Array ( [b] => book )
if(!array_key_exists("a",$arr))
$arr['a'] = 'apple';
print_r($arr); // prints Array ( [b] => book [a] => apple )
?>
If you want to use isset condition try like this:
$arr = array();
$arr['b'] = 'book';
$flag = 0;
foreach($arr as $key=>$val) {
print "key=>$key\n";
if(!isset($arr["a"]))
{
$flag = 1;
}
}
if(flag)
{
$arr['a'] = 'apple';
}
print_r($arr);
How about using for and realtime array_keys()?
<?php
$arr = array();
$arr['b'] = 'book';
for ($x=0;$x<count($arr); $x++) {
$keys = array_keys($arr);
$key = $keys[$x];
print "key=>$key\n";
if(!isset($arr['a']))
$arr['a'] = 'apple';
}

Looping through PHP array in foreach and give each $value a new variable name

I want to take an array, loop it with a foreach loop, and have each array value be sent through a class to get data from a database. This is the code I am currently using:
foreach ($unique_category as $key => $value)
{
$category = $value;
$value = new database;
$value->SetMysqli($mysqli);
$value->SetCategory($category);
$value->query_category();
${"$value_category"} = $value->multi_dim_array();
print_r(${"$value_category"});
echo "<br /><br />";
}
print_r($unique_category[0]."_category");
I want the variable $unique_category[0]."_category" to be ${"$value_category"}.
Currently, the ${"$value_category"} in the foreach loop prints out the correct value/array, while $unique_category[0]."_category" just prints person_category (person being the first value in that array).
How would I go about making $unique_category[0]."_category" print the same thing as ${"$value_category"}?
Thank you
EDIT:
The foreach loop is making a multidimensional array that looks something like this Array ( [0] => Array ( [0] => Home [1] => 9.8 ) [1] => Array ( [0] => Penny [1] => 8.2 )) I want to be able to print out this array outside the foreach loop, with each md array having its own variable name so I can print them out wherever and whenever I want.
Testing without the object
<?php
$unique_category_list = array('foo', 'bar', 'baz');
foreach ($unique_category_list as $key => $value)
{
$category = $value;
$value_category = $value."_".$category;
$unique_category = $unique_category_list[$key]."_category";
$unique_category = ${"$value_category"} = $key;
print_r($unique_category_list[$key]."_category");
echo "\n\n";
}
?>
Outputs:
foo_category
bar_category
baz_category
With the object
<?php
// note that $unique_category is now $unique_category_list && $value is now $category
foreach ($unique_category_list as $key => $category)
{
$database = new Database();
$database->setMysqli($mysqli);
$database->setCategory($category);
$database->query_category();
// http://www.php.net/manual/en/language.oop5.magic.php#object.tostring
// this will invoke the `__toString()` of your $database object...
// ... unless you meant like this
// $value_category = $category."_".$category;
$value_category = $database."_".$category;
$unique_category = $unique_category_list[$key]."_category";
// http://stackoverflow.com/questions/2201335/dynamically-create-php-object-based-on-string
// http://stackoverflow.com/questions/11422661/php-parser-braces-around-variables
// http://php.net/manual/en/language.expressions.php
// // http://php.net/manual/en/language.variables.variable.php
// 'I want the variable $unique_category[0]."_category" to be ${"$value_category"}.'
$unique_category = ${"$value_category"} = $database->multi_dim_array();
}
print_r($unique_category_list[0]."_category");
echo "<br><br>\n\n";
?>

PHP Multidimensional Array push and loop

I'm having some trouble understanding the coding in PHP, when it comes to multidimensional arrays and how to push.
The idea is to push a "Attribute" and a "Attribute value"
I have tried the formula below
$i = 0;
$array = array();
foreach($node as $a)
{
$strAtt = $node->PROP[$i]->attributes();
$strVal = $node->PROP[$i]->PVAL;
$output = $output.$strAtt." : ".$strVal."<BR>";
$array[] = ($strAtt => $strVal);
The $array[] = ($strAtt => $strVal); doesnt give me much success.
I have tried array_push($array, $strAtt => $strVal) - no luck..
As an extra questions, how do I loop trough the array and print me multidimensional values ?.
NEW CODE
while ($z->name === 'RECORD')
{
$node = new SimpleXMLElement($z->readOuterXML());
$Print = FALSE;
$output = "";
$i = 0;
foreach($node as $a)
{
$strAtt = $node->PROP[$i]->attributes();
$strVal = $node->PROP[$i]->PVAL;
$output = $output.$strAtt." : ".$strVal."<BR>";
$array[$strAtt] = $strVal;
if(($i == 6) && ($node->PROP[$i]->PVAL == $ProductLookup))
{
$Print = TRUE;
$Product = $node->PROP[$i]->PVAL;
}
$i++;
}
if($Print == TRUE) {
echo $output;
echo "Product : ".$Product."<br>";
var_dump($array);
}
//print_r($array);
$print = FALSE;
// go to next <product />
$z->next('RECORD');
}
New code added. For some reason my $array is totally empty when i dump it, although my $Output is full of text ?
It sounds like you are wanting an "associative" array and not necessarily a multi-dimensional array. For associative arrays you don't use array_push. Just do this:
$array[$strAtt] = $strVal;
Then to loop the array just do this:
foreach ($array as $key => $value) {
echo "$key = $value\n";
}
Go through array in php , you will understand how array works in php.
Besides if you want to add an element to a multidimensional array you can achieve like this :
$node = array ("key1"=> array (a,b) , "key2"=> array (c,d));
$array = array();
foreach ($node as $key=>$value) {
$array [$key] = $value;
}
This will be the resulting $array after the loop :
array (
"key1"=> array (
a,b
) ,
"key2"=>
array (c,d)
)
Hope that helps , happy coding :)

Categories