0

I'm learning OOP and I whould create a list of objects in an array, but my code return the last array I have search here, but haven't found a solution or idea how to do this.

Excepct

        "MerchantDefinedFields":[  
        {  
           "Id":2,
           "Value":"[email protected]"
        },
        {  
           "Id":4,
           "Value":"Web"
        },
        {  
           "Id":9,
           "Value":"NAO"
        },
        {  
           "Id":83,
           "Value":"Field"
        },
        {  
           "Id":84,
           "Value":"Only"
        }
     ]

My code

            $MDDs = array(
                array("Id" => 2, "Value" => "[email protected]"), 
                array("Id" => 4, "Value" => "Web"),
                array("Id" => 9, "Value" => "NO"),
                array("Id" => 83, "Value" => "Field"),
                array("Id" => 84, "Value" => "Only")
            );
             
            foreach($MDDs as $MDD){
                $abac = array("Id" => $MDD['Id'], "Value" => $MDD['Value']);
            }

Result

    Array
(
    [Id] => 84
    [Value] => PROPRIO
)
1
  • Isn't your output exactly the same as the input? Also just to point out that you are creating a nested array and not an array of objects. Commented Nov 12, 2020 at 18:11

3 Answers 3

2

Your foreach() is re-setting $abac every time it goes through the loop. So on the last time it runs, it will set the variable to the last item in your array.

Instead of setting the variable each time, try adding the key->value to an array (or something like that, depending on what you want):

$abac = [];
foreach($MDDs as $MDD){
    $abac[] = array("Id" => $MDD['Id'], "Value" => $MDD['Value']);
}

It's hard to create the exact right answer for you, since it's unclear what you're trying to accomplish, but this should at least point you in the right direction.

Sign up to request clarification or add additional context in comments.

Comments

0

For simple answer :- You don't need foreach loop to get the desired result you can simply use built-in php function to convert your array to JSON

$abac = json_encode ( $MDDs);

Now coming to your problem :-

you are re-assigning the $abac variable in loop instead of adding values to it like .

$abac = [];
foreach($MDDs as $MDD){
    $abac[] = array("Id" => $MDD['Id'], "Value" => $MDD['Value']);
}

Comments

0

The best way to do it is to declare the $abac outside of the foreach and then use the array_push method like this:

$abac = array();

foreach($MDDs as $MDD)
{
    array_push($abac, array("Id" => $MDD['Id'], "Value" => $MDD['Value']));
}
print_r($abac);

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.