0

I am trying to add values to an array using the code below but it only seems to result in 1 item (last in the loop) being added to the array.

$awin_products = array();

foreach($awinprices as $value){
foreach($value as $obj){        
    $awin_products[name] = (string)$obj->sName;
    $awin_products[imageUrl] = (string)$obj->sAwThumbUrl;
    }
}
print_r($awin_products); 

This is probably quite simple to fix but so far I've not found an answer.

EDIT: I am looking for this output:

Array
(
    [0] => Array
        (
            [name] => Item 1 Name
            [imageUrl] => http://example.com/item1.jpg
        )
    [1] => Array
        (
            [name] => Item 2 Name
            [imageUrl] => http://example.com/item2.jpg
        )
    [2] => Array
        (
            [name] => Item 3 Name
            [imageUrl] => http://example.com/item3.jpg
        )
    [3] => Array
        (
            [name] => Item 4 Name
            [imageUrl] => http://example.com/item4.jpg
        )
)

2 Answers 2

4

You're over-writing the same values on each run:

foreach($value as $obj){         
    $awin_products[name] = (string)$obj->sName; 
    $awin_products[imageUrl] = (string)$obj->sAwThumbUrl; 
} 

You need to change where you're writing to; maybe with something like this:

$i = 0;
foreach($awinprices as $value){ 
    $awin_products[$i] = array();
    foreach($value as $obj){  
        $awin_products[$i][]['name'] = (string)$obj->sName; 
        $awin_products[$i][]['imageUrl'] = (string)$obj->sAwThumbUrl; 
    } 
    $i++;
}
Sign up to request clarification or add additional context in comments.

6 Comments

Or even better $awin_products[$i]['name']
You're right - that is more elegant. Can you edit my answer to add it?
nerdklers wrote what i was thinkin about
In this solution array will be overwritten for each $awinprices
@AlexanderLarikov - I think that edit should solve it. Thanks for the heads-up!
|
2

You need following

$awin_products = array();
$i = 0;
foreach($awinprices as $value){
    foreach($value as $obj){        
        $awin_products[$i]['name'] = (string)$obj->sName;
        $awin_products[$i]['imageUrl'] = (string)$obj->sAwThumbUrl;
        $i++;
    }
}

Then you'll get structure like this:

Array
(
            [0] => Array
                (
                    [name] => name
                    [imageUrl] => url
                )
            [1] => Array
                (
                    [name] => name1
                    [imageUrl] => url1
                )
)

1 Comment

@sr83 it was hard to get what you want since you didn't posted desired structure. See edited answer

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.