Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the property name of the first property in an stdClass in PHP

Tags:

php

php-5.6

I have an array that consists of many stdClasses after doing a json_decode on a json string.

It looks like this:

product: array(3)
0: stdClass
   PropertyAbc: "Product 1|Product 5"
1: stdClass
   PropertyXyz: "Product 2|Product 9|Product 10"
2: stdClass
   PropertyEfg: "Product 3|Product 12"

I need to turn this into a pipe delimited string of all values in the following format: PropertyName>Value as my end result:

PropertyAbc>Product 1|PropertyAbc>Product 5|PropertyXyz>Product 2|PropertyXyz>Product 9|PropertyXyz>Product 10|PropertyEfg>Product 3|PropertyEfg>Product 12

Here is how I attempted to do it, but cant figure out how to get the value and name of the first property when looping through the stdClasses (note: there will always be only one property for each stdClass):

foreach ($json->products as $product) {
    // Put all products in an array
    $arr = explode('|', $NEED-VALUE-OF-FIRST-PROP);

    // Loop through array and combine values
    foreach ($arr as $key => $value) {
        $arr[$key] = $NEED-NAME-OF-FIRST-PROP . ">" . $value;
    }
}
like image 271
Blake Rivell Avatar asked Oct 22 '25 19:10

Blake Rivell


1 Answers

get_object_vars is useful to get the object properties as an array and work from there.

 $p1 = new StdClass();
 $p1->PropertyAbc = "Product 1|Product 5";

 $p2 = new StdClass();
 $p2->PropertyXyz = "Product 2|Product 9|Product 10";

 $p3 = new StdClass();
 $p3->PropertyEfg = "Product 3|Product 12";

 $products = [ $p1, $p2, $p3 ];
 foreach ($products as $product) {
    $productArray = get_object_vars($product);
    $productPropName = array_keys($productArray)[0];
    $productPropsValues = explode('|', array_values($productArray)[0]);
    foreach ($productPropsValues as $productPropsValue) {
        $result[] = $productPropName . '>' . $productPropsValue;
    }
}

var_dump(implode('|', $result));

string(155) "PropertyAbc>Product 1|PropertyAbc>Product 5|PropertyXyz>Product 2|PropertyXyz>Product 9|PropertyXyz>Product 10|PropertyEfg>Product 3|PropertyEfg>Product 12"

like image 172
William J. Avatar answered Oct 25 '25 10:10

William J.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!