so lets say i have a object like this
{
"status": "AlreadyVerified"
}
and i want to store propert key in variable so i can access property using that variable like
$key = 'status';
echo $object->$key
but what if i have a nested object like
{
"extra_info": {#305 ▼
+"status": "AlreadyVerified"
}
}
this wouldn't work
$key = 'extra_info->status';
echo $object->$key
how can i store nested object chain in a variable so i can access its property using that variable ?
preferably some way that works for both nested and flat objects (i guess that's what the're called !)
It can be possible by write helper function like this:
function deepFind($o, $key) {
$key = explode('->', $key);
$value = $o;
foreach ($key as $i=>$k) {
if (is_object($value) && isset($value->{$k})) {
$value = $value->{$k};
} elseif (is_array($value) && isset($value[$k])) {
$value = $value[$k];
} elseif ($i == count($key) - 1) {
$value = null;
}
}
return $value;
}
Usage:
$o = (object)[
"extra_info" => (object)[
"status" => "AlreadyVerified"
]
];
echo deepFind($o, 'extra_info->status');
Online demo
This is one way to do it, albeit potentially insecure depending on where $key comes from:
<?php
$object = new stdClass();
$object->extra_info = new stdClass();
$object->extra_info->status = 'AlreadyVerified';
$key = 'extra_info->status';
eval( 'echo $object->'.$key.';' );
Output:
AlreadyVerified
Additionally, if you wanted to parse $key then you could use a recursive function to access the nested value.
Related
I have a multi-dimensional array with key value pairs. Some of the values of the keys are arrays, and some of the values in that array are arrays as well. It is only 3 branches deep (for now), but I am trying to recursively loop through the array, save the key for each level of the branch, and create a new array when it reaches a string that also mimics the structure of the original array. When it reaches a string, there should be a new object instantiation for each value.
The code below sort of does this, but only creates a flat array.
foreach ($data as $key => $value) {
if (!is_array($value)) {
$a_objects[$key] = new Component([$key], $value);
} else {
foreach ($value as $valueKey => $valueValue) {
if (!is_array($valueValue)) {
$a_objects[$key . "_" . $valueKey] = new Component([$key, $valueKey], $valueValue);
} else {
foreach ($valueValue as $k => $v) {
$a_objects[$key . "_" . $valueKey . "_" . $k] = new Component([$key, $valueKey, $k], $v);
}
}
}
}
Here is my own best attempt at this but it does not seem to save into the b_objects after some testing it does not seem to be saving the object instances.
$b_objects = [];
function create_r($data, $id)
{
foreach ($data as $key => $value) {
if (is_array($value) == true) {
array_push($id, $key);
create_r($value, $id);
} else {
array_push($id, $key);
$b_objects[$key] = new Component($id, $value);
$id = [];
}
}
}
$id = [];
create_r($data, $id);
echo "this is b_objects";
echo "<pre>";
print_r($b_objects);
echo "</pre>";
I verified that $id array contains the right "keys". I feel like this solution is pretty close but I have no idea how to use my $id array to mimic the structure of the $data.
I want to be able to say $b_objects[$level1key][$level2key][$level3key]...[$leveln-1key] = new Component...
Thanks!
I suggest you pass $b_objects by reference to your create_r() function. Otherwise each function call will instantiate a new $b_objects variable which is not used anywhere in the code afterwards.
Passing by reference allows the function to actually change the input array. Notice the & sign in the function declaration.
function create_r($data, $id, &$res)
{
foreach ($data as $key => $value) {
if (is_array($value) == true) {
array_push($id, $key);
create_r($value, $id, $res);
} else {
array_push($id, $key);
$res[$key] = new Component($id, $value);
$id = [];
}
}
}
$id = [];
$b_objects = [];
create_r($data, $id, $b_objects);
EDIT: ten months later, I'm still back to this.. still can't figure it out :(
I can search for a string in an array no problem; this works:
if (in_array('animals', $value[tags])){
echo "yes";
}
But how can I check for a variable in the array? This doesn't seem to work:
$page_tag = 'animals';
if (in_array($page_tag, $value[tags])){
echo "yes";
}
I'm guessing I'm missing some simple syntax doodad?
The array is massive, so I'll try and show a sample of it. It is stored on a separate php file and "included" in other places.
global $GAMES_REPOSITORY;
$GAMES_REPOSITORY = array (
"Kitten Maker" => array (
"num" => "161",
"alt" => "Kitten Maker animal game",
"title" => "Create the kitten or cub of your dreams!",
"tags" => array ("animals", "feline", "cats", "mega hits"),
),
}
Here's a larger part of the code, to put into context. It pulls from the array of ~400 games, and pulls the ones with a specific tag:
function array_subset($arr) {
$newArray = array();
foreach($arr as $key => $value) {
if (in_array($page_tag, $value["tags"])){
if(is_array($value)) $newArray[$key] = array_copy($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
}
return $newArray;
}
function array_copy($arr) {
$newArray = array();
foreach($arr as $key => $value) {
if(is_array($value)) $newArray[$key] = array_copy($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
return $newArray;
}
$games_list = array();
$games_list = array_subset($GAMES_REPOSITORY);
$games_list = array_reverse($games_list);
Oh, an interesting hint. Elsewhere it DOES work using $_GET:
if (in_array($_GET[tagged], $value[tags])){
The in_array() function can check variables, so it is likely that your problem comes from somewhere else. Verify that you've defined your constant tags correctly. If it's not defined, it might not work depending on your PHP version. Some versions just assume that you wanted to write the string tags instead of a constant named tags.
Your code works. Here's a full example that I've tested that works well:
<?php
const tags = "tags";
$page_tag = 'animals';
$value = array('tags' => array("fruits", "animals"));
if (in_array($page_tag, $value[tags])){
echo "yes";
}
You have an array of arrays, so in_array() wont work as you have written it as that test for existence in an array, not a subarray. You may as well just loop through your arrays like this:
foreach($GAMES_REPOSITORY as $name =>$info) {
if(in_array($page_tag, $info['tags']))
{ whatever }
}
If that is not fast enough you will have to cache your tags by looping ahead of time and creating an index of tags.
I finally got it to work! I don't entirely understand why, but I had to feed the variable into the function directly. For some reason it wouldn't pull the variable from the parent function. But now it works and it even takes two dynamic variables:
function array_subset2($arr, $tag1, $tag2) {
$newArray = array();
foreach($arr as $key => $value) {
if (in_array($tag1, $value['tags'])){
if (in_array($tag2, $value['tags'])){
if(is_array($value)) $newArray[$key] = array_copy2($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
}
}
return $newArray;
}
function array_copy2($arr) {
$newArray = array();
foreach($arr as $key => $value) {
if(is_array($value)) $newArray[$key] = array_copy2($value);
else if(is_object($value)) $newArray[$key] = clone $value;
else $newArray[$key] = $value;
}
return $newArray;
}
$games_list = array();
$games_list = array_subset2($GAMES_REPOSITORY, $page_tag, $featured_secondary_tag);
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);
}
}
How would I go about accessing these elements from a Shopify JSON in PHP
JSON:
{
"orders":[
{ "note_attributes":[
{
"name":"field1",
"value":"xxxxxxxxxxxx"
},
{
"name":"field2",
"value":"xxxxxx"
},
{
"name":"field3",
"value":"xxxxxx"
}
],
This is just snippet of the object. How would I access each value and assign it to the name? Eg this $req['account_id'] would equal the value for that name tag. This is how am trying to do it but it's not working:
foreach ($order['note_attributes'] as $attributes) {
$req = array();
$req[$attributes->name] = $attributes[$attributes->value];
}
I would then like to echo $req['account_id'] and that would = xxxxxxxxx#gmail.com but it's not working any suggestions or fixes?
When iterating over Objects properties, one approach is to use (as you have) foreach
// accessing property
foreach ($objects as $object) {
echo $object->property;
}
// accessing key-value pair
foreach ($object as $key => $value) {
echo "$key => $value\n";
}
An example:
$attributes = array();
.
.
foreach($note_attributes as $note_attribute) {
$key = $note_attribute['name'];
$value = $note_attribute['value'];
$attributes[$key] = $value;
}
The structure should be in key-value pairs. ie.
attributes [
"account1234" => "abc#xxx.com",
"account_password" => "asdasdasd"
]
Hope this helps.
Update: as Roopendra mentioned, json_decode() with a TRUE flag with return an associative array, else stdClass.
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;