Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have an array of objects, each object contains a bunch of values, two of which are an int and a string. I need to loop over the objects and pull out the string and int and place them into an associative array, where each string associates with each int. How would I go about doing this?

This is what I have so far:

foreach( $fileobject as $p ) {
    $program_number = $p['number'];
    $filename = $p['InputFile']['filename'];
}

$fileobject is the array of objects. 'number' is the int, and 'filename' is the string. What is the syntax for putting the 'number' and 'filename' together into an associative array. There are undetermined amount of objects in the initial array.

share|improve this question

1 Answer 1

$result = array();
foreach( $fileobject as $p ) {
    $program_number = $p['number'];
    $filename = $p['InputFile']['filename'];
    $result[] = array( 'number' => $program_number, 'filename' => $filename);
}

However you mentioned that you're using an array of objects, so this is likely the correct syntax:

$result = array();
foreach( $fileobject as $p ) {
    $program_number = $p->number;
    $filename = $p->InputFile->filename;
    $result[] = array( 'number' => $program_number, 'filename' => $filename);
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.