phparraysexplode

Split a delimited string and create single-element associative rows from the values with a static key


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.


Solution

  • 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);
    }