skip to Main Content

I’m trying to figure out how to implode a json array coming from an axios call, within a php file. I currently have this function where I toggle between dumping out the array and then trying to dump the imploded version but that fails stating that it’s an invalid argument for a foreach.

PHP file:

public function getResults(array $num = []){
    dd($num);
    dd(implode(", ", array_map(function($obj) { foreach ($obj as $p => $v) { return $p;} }, $num)));
} 

The dd($num) call shows this in my network console:

array:2 [
  0 => "{"number":"115"}"
  1 => "{"number":"135"}"
]

How can I implode this to look like 115,135?

2

Answers


  1. You should use php’s built in function json_decode($data) to decode json.

    You Will not get it in the format you have show, but as a stdClass by default.

    If you oass a 2nd argument to json_decode (true or false) you will get it as and associative array og you are more comdortable with that.

    I would have provided a better usage example, but the editor is not coorporating on my mobile device.

    Login or Signup to reply.
  2. <?php
    
    function getResults(array $num = []): string
    {
        return implode(", ", array_map(fn ($obj) => json_decode($obj)->number , $num));
    }
    
    
    $json = ['{"number":"115"}','{"number":"135"}'];
    
    echo getResults($json);
    

    Test https://3v4l.org/HUmuM

    Issues with your code

    1. PHP receives JSON as a string. So you need to decode that string so it makes sense for your code as a data structure.

    2. You have an array of objects. array_map already iterates through the array and exposes the stringified objects inside its scope. So I see no need for the extra loop.

    3. Even if you did decode the object as an associative array you could just do return $obj['number']. ($obj as $p => $v) { return $p;} would always return "number" which is the key.


    Fix for the comment feedback

    My code is throwing an error at => (I’m running PHP 7.1)

    Parse error: syntax error, unexpected ‘=>’ (T_DOUBLE_ARROW), expecting ‘)’ in…

    https://www.php.net/manual/en/functions.arrow.php

    Arrow functions were introduced in PHP 7.4 as a more concise syntax for anonymous functions.

    return implode(", ", array_map(function ($obj) {
        return json_decode($obj)->number;
    }, $num));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search