2

I'm trying to make this json string:

{phones:[{"numbers":12345},{"numbers":67890}]}

How can I achieve that from an exploded string?

$phones = '123456;7890';
$phones = explode(';', $phones);

I've tried using foreach like this:

foreach ($phones as $phone) {
    $array["numbers"] = $phone;
}

But it keep replacing the first key. and yes I read that PHP array can't have the same key on the same level of an array.

2 Answers 2

2

The problem is that you're setting the 'numbers' key in the array on each iteration. Instead, you want the result to be an array where every element is an associative array where the key is 'numbers' and the value is a number:

$phones = "123456;7890";
$exploded = explode(';', $phones);
$result = array();
foreach ($exploded as $elem) {
    $result[] = array('numbers' => $elem);
}
Sign up to request clarification or add additional context in comments.

Comments

0

Here's a functional-style approach. Explode on semicolon then iterate those elements with array_map(). In the callback declare a variable with your desired key, then use get_defined_vars() to create the single element associative rows. Assign the populated array to the key phones, then json_encode().

Code: (Demo)

$phones = '123456;7890';
echo json_encode(['phones' => array_map(
         fn($numbers) => get_defined_vars(),
         explode(';', $phones)
     )]);

Output:

{"phones":[{"numbers":"123456"},{"numbers":"7890"}]}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.