0

I want to create this response

'Points' => array(
    'Point' => array(
                    array(
                          'Type' => 'value',
                          'Zone'   => 'value
                    ),
                    array(
                          'Type' => 'value',
                          'Zone'   => 'value'
                    )
              )  
    )

My code gives me this:

array:1 [▼
  "Points" => array:1 [▼
    "Point" => array:2 [▼
      "Type" => 4
      "Zone" => "Front"
    ]
  ]
]

Which is very close, unfortunately de Points key is being overwritten anyone knows what I am doing wrong?

$pointsObject = array();
foreach ($points as $point) {
    $pointsObject['Points']['Point'] = array(
        'Type'  => $point->type,
        'Zone'  => $point->zone
    );
}

dd($pointsObject);
4
  • @JohnConde Yes I am aware of that but look at my expected result. Does this mean it's impossible to achieve this? Commented Oct 3, 2017 at 14:40
  • $pointsObject['Points']['Point'][] = ` <- that's what you're missing Commented Oct 3, 2017 at 14:40
  • 1
    You could be looking for $pointsObject['Points']['Point'] [] = instead of $pointsObject['Points']['Point'] = to append instead of overwrite Commented Oct 3, 2017 at 14:40
  • @kharhys It works thanks :) Commented Oct 3, 2017 at 14:42

2 Answers 2

3

You are overwriting the value of $pointsObject['Points']['Point'] in every loop. For to avoid overwrite its value you should add [] at the end. Example:

$pointsObject['Points']['Point'][] = array(...);

That push new values into the array in every loop.

Regards.

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

Comments

1

Try like this

Just add [] after ['Points']['Point']

$pointsObject = array();
foreach ($points as $point) {
    $pointsObject['Points']['Point'][] = array(
        'Type'  => $point->type,
        'Zone'  => $point->zone
    );
}

dd($pointsObject);

1 Comment

"Try this" does not make for a good answer. You should explain how and why this solves their problem. I recommend reading, "How do I write a good 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.