简体   繁体   中英

PHP Object array access with variable

I have a sample object array as a variable $xmlobj

SimpleXMLElement Object(
[SearchId] => 10769920113727_1556288871357_170040
[Categories] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [total_subcategories] => 1
            )

        [SubCategory] => SimpleXMLElement Object
            (
                [Title] => Reproductor MP3 y Multimedia
                [Value] => 122701
                [NumberOfProducts] => 1
            )

    )

[Products] => SimpleXMLElement Object
    (
        [@attributes] => Array
            (
                [totalResultsAvailable] => 1
                [firstResultPosition] => 1
                [totalResultsReturned] => 1
                [currency] => EUR
                [totalMerchantsAvailable] => 1
                [searchOperator] => and
            )

        [Product] => SimpleXMLElement Object
            (
                [Offer] => SimpleXMLElement Object
                    (
                        [@attributes] => Array
                            (
                                [id] => f94af9ec5186b53051c9ccf083ebddec
                                [type] => MANUFACTURER_PRODUCTS
                            )

                        [Title] => Apple iPod Nano 6 8 GB Gris
                        [Description] => iPod Nano 6 8 GB - Gris
                        [LastModified] => 2019-04-26 01:10:56
                        [MobileFriendly] => false
                        [Merchant] => SimpleXMLElement Object
                            (
                                [@attributes] => Array
                                    (
                                        [id] => 15348713
                                    )

                                [Name] => Backmarket

                            )

                        [Price] => SimpleXMLElement Object
                            (
                                [@attributes] => Array
                                    (
                                        [currency] => EUR
                                    )

                                [Price] => 99.99
                                [DeliveryCost] => 19.9
                                [DeliveryCostDetails] => SimpleXMLElement Object
                                    (
                                        [DeliveryCost] => 19.9
                                    )

                                [TotalPrice] => 119.89
                                [PriceWithoutRebate] => 190
                                [Rebate] => 47
                            )

                        [ProductClass] => 2
                        [Availability] => 1
                        [DeliveryTime] => 24H / 4 días laborables
                        [Promo] => SimpleXMLElement Object
                            (
                            )

                        [OffensiveContent] => false
                        [FinancingOption] => SimpleXMLElement Object
                            (
                            )

                        [MerchantCategory] => Alta Tecnología  Imágenes y sonidos  Reproductor de MP3 Y MP4
                        [Brand] => Apple
                        [BrandId] => 211
                        [GreenProduct] => false
                    )

            )

    )

Now when I want to access eg price i do it like this:

$product_total_price = $xmlobj->Products->Product->Offer->Price->TotalPrice;

And it's OK - I get what I want, but I am having issue when I want "dynamically" to change what I am looking for like:

$search_part = "Products->Product->Offer->Price->TotalPrice";
$product_total_price = $xmlobj->$search_part;

I obviously get nothing... even when I try:

$product_total_price = $xmlobj."->".$search_part;

So my question is... how to do it ? :)

Thanks !

You will have to construct the path by exploding into an array, then looping to get each property.

For example...

$searchPart = "Products->Product->Offer->Price->TotalPrice";
$searchPath = explode('->', $searchPart);

$current = $xmlobj;
foreach ($searchPath as $segment) {
    $current = $current->$segment;
}
var_dump($current);

or you can convert it to an array and then you will be able to get your attributes

$xml = simplexml_load_string($xmlobj);
$json = json_encode($xml);
$arr = json_decode($json,TRUE);

$parseString = 'Products->Product->Offer->Price->@attributes->currency';
$parsePath = explode('->', $parseString);

$current = $arr;
foreach ($parsePath as $segment) {
    $current = $current[$segment];
}
var_dump($current);

You can take a look at eval that take your code as a string and evaluates it, but I strongly discourage its usage because it's a potentially (and very big) security hole.

Instead you could use explode passing as first argument -> and then loop over the resulting array to get the value you need:

$search_part = "Products->Product->Offer->Price->TotalPrice";
$chunks = explode("->", $search_part);

foreach ($chunks as $chunk) {
  $temp = $xmlobj[$chunk];
}

$product_total_price = $temp;

or something similar, and then you will get you price dynamically

Note that if $xmlObj is of type Object you will need to use $xmlObj->{$chunk} instead of $xmlobj[$chunk]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM