1

I've got an object, containing an array of objects, containing an array of values:

stdClass Object (
    [devices] => Array (
    [0] => stdClass Object ( 
        [location] => 1
        [delegate] => 
        [type] => 1 
        [id] => 1234 
        [IP] => 1.2.3.4
        [name] => host1
        [owner] => user6 
        [security] => 15
        )
    [1] => stdClass Object (
        [location] => 2
        [delegate] => 
        [type] => 1 
        [id] => 4321 
        [IP] => 4.3.2.1
        [name] => host2
        [owner] => user9 
        [security] => 15
        )
    )
)

I want to extract just the id and name into an array in the form of: $devices['id'] = $name;

I considered using the array_map() function, but couldn't work out how to use it... Any ideas?

3
  • Why not use a function which accepts the object and returns your array then call it: $devices = myfunction($my_object); Commented Oct 20, 2016 at 23:46
  • May seem trivial but that structure dont make no sense man Commented Oct 20, 2016 at 23:52
  • Show us a print_r($top_object) Commented Oct 20, 2016 at 23:53

3 Answers 3

1

This will generate you a new array like I think you want

I know you says that delegate is an object but the print does not show it that way

$new = array();
foreach($obj->devices as $device) {
    $new[][$device->id] = $device->name;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Would something like this not work? Untested but it cycles through the object structure to extract what I think you need.

$devices = myfunction($my_object);

function myfunction($ob){
    $devices = array();
    if(isset($ob->devices)){
        foreach($ob->devices as $d){
            if(isset($d->delegate->name && isset($d->delegate->id))){
                $devices[$d->delegate->id] = $d->delegate->name;
            }
        }
    }
    return($devices);
}

Comments

0

Im usually using this function to generate all child and parent array stdclass / object, but still make key same :

function GenNewArr($arr=array()){
    $newarr = array();
    foreach($arr as $a=>$b){
        $newarr[$a] = is_object($b) || is_array($b) ? GenNewArr($b) : $b ;
    }
    return $newarr;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.