Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Accessing named array elements issue

Tags:

arrays

php

I have an array which is generated from an XML file and it shows me like below when printed with print_r

Array
(
    [cxname] => Global CX 87 123
    [ipaddress] =>  66.240.55.87
    [slots] => Array
        (
            [slot] => Array
                (
                    [0] => Array
                        (
                            [slotno] =>  1
                            [cardtype] => 0x24 
                            [modelno] =>  OP3524J
                            [label1] => OP 
                            [label2] =>  Module
                            [severity] => Minor
                        )

                    [1] => Array
                        (
                            [slotno] =>  2
                            [cardtype] => 0x25 
                            [modelno] =>  OP3524K
                            [label1] => OP 
                            [label2] =>  Module
                            [severity] => Major
                        )

                )

        )

)

When I print like this, it shows nothing

 echo $dataArray->cxname;

But following code works and prints "Global CX 87 123 "

 echo $dataArray["cxname"];

How can I make it work as above example.

like image 213
AjayR Avatar asked Dec 28 '22 18:12

AjayR


2 Answers

Just do this:

$dataArray = (object)$dataArray;

It'll convert the array in an stdClass object and allow you to use it that way. Please note that this will only convert the first level for the array. You'll have to create a function to recurse through the array if you want to access all levels that way. For example:

<?php
function arrayToObject($array) {
    if(!is_array($array)) {
        return $array;
    }

    $object = new stdClass();
    if (is_array($array) && count($array) > 0) {
      foreach ($array as $name=>$value) {
         $name = strtolower(trim($name));
         if (!empty($name)) {
            $object->$name = arrayToObject($value);
         }
      }
      return $object; 
    }
    else {
      return FALSE;
    }
}

For more information, have a look at http://www.richardcastera.com/blog/php-convert-array-to-object-with-stdclass. To find out about typecasting, you can also read http://www.php.net/manual/en/language.types.object.php#language.types.object.casting.

like image 151
Francois Deschenes Avatar answered Jan 09 '23 01:01

Francois Deschenes


This:

echo $dataArray["cxname"];

is the way you access array elements. But this:

echo $dataArray->cxname;

is the way, you access class members.

If you want to access the data as class members, you have to use a xml parser which returns classes (or objects), not arrays.

If you have got the XML string, you can parse it into an object by using simplexml_load_string().

like image 37
Florian Avatar answered Jan 09 '23 01:01

Florian