Search code examples
phparraysdynamic-arrays

How do I add an item that contains a comma to an array?


I have an array of objects that I am looping through. I need to create an array that contains items in the format LASTNAME, FIRSTNAME.

When I do this I end up with an array of lastname, firstname, lastname, firstname etc. because it interprets my comma in the text as a separator for two array values.

JSON (example):

[
   {"lastname":"Levy","firstname":"Robert"},
   {"lastname":"Johannenson","firstname":"Svenn"},
   {"lastname":"Smith","firstname":"Albertson"}
]

then

$authors = array();

for ($i = 0; $i < count($index); ++$i) {

$at = trim($index[$i]->lastname) . ", " . trim($index[$i]->firstname); $authors[] = $at; }

Then $authors contains

["Levy","Robert","Johannenson","Svenn","Smith","Albertson"]

instead of the desired:

["Levy, Robert","Johannenson, Svenn","Smith, Albertson"]

I'm really not new to this but this has me stumped. I could try some kind of character replacement after the array is made (e.g. using | as a separator then doing a str_replace or something) but am looking for a more elegant way.


Solution

  • Here is your example

    $index = json_decode('[
       {"lastname":"Levy","firstname":"Robert"},
       {"lastname":"Johannenson","firstname":"Svenn"},
       {"lastname":"Smith","firstname":"Albertson"}
     ]');
    $authors = array();
    for ($i = 0; $i < count($index); ++$i){
        $at = trim($index[$i]->lastname) . ", " . trim($index[$i]->firstname);
        $authors[] = $at;
    }  
    

    and here is the output of $authors

    array(3) {
      [0]=>
      string(12) "Levy, Robert"
      [1]=>
      string(18) "Johannenson, Svenn"
      [2]=>
      string(16) "Smith, Albertson"
    }
    

    So everything seems to be correct.

    Can you provide full source code?