0

Why I can't insert an associative array inside another array? How can I do that? [PHP]

I try get somenthing like this:

    [0] => ['name' => 'namedperson' , 'type' => 'text' ,'id'=>'ahushaus29293' ]  
    [1] => [...] 
    ...

Example:

public function getArrayWithCustomFields($boardId, $client){
    $customFields = $client->getBoardCustomFields($boardId);
    foreach($customFields as $customField){
        array_push($array_custom_fields, array('name' => $customField->name, 'type' => $customField->type, 'id' => $customField->id));
    }
    return $array_custom_fields;
}
8
  • @ArSeN They're not trying to merge arrays, they want a 2-dimensional array. I think their code should work.
    – Barmar
    Commented Jan 14, 2021 at 21:02
  • Assuming $customFields is an array of objects.
    – Barmar
    Commented Jan 14, 2021 at 21:03
  • Oooh I see, first part was just edited in later. Sorry about that
    – ArSeN
    Commented Jan 14, 2021 at 21:04
  • @ArSeN I just fixed the formatting, I didn't change it.
    – Barmar
    Commented Jan 14, 2021 at 21:04
  • My bad! @OP - what result are you getting instead of what you are trying to achieve?
    – ArSeN
    Commented Jan 14, 2021 at 21:05

1 Answer 1

1

You should initialize $array_custom_fields, as well as, check if the returned value from getBoardCustomFields is an array.

public function getArrayWithCustomFields($boardId, $client)
{
    // Init the array
    $array_custom_fields = [];
    $customFields = $client->getBoardCustomFields($boardId);

    // Check if the returned value from $client->getBoardCustomFields() is an array.
    if (is_array($customFields))
    {
        foreach($customFields as $customField) {
            array_push(
                $array_custom_fields,
                [
                    'name' => $customField->name,
                    'type' => $customField->type,'id' => $customField->id
                ]
            );
        }
    }

    return $array_custom_fields;
}

P.S: it's a good practice to always initialize your variables in PHP even tho it doesn't force you to do it.

4
  • awesome! please consider to mark this question as answered! thanks
    – parse
    Commented Jan 14, 2021 at 21:21
  • Why "it's a good practice to always initialize your variables in PHP"? Is there a specific reason? Commented Jan 14, 2021 at 22:09
  • @AbsoluteBeginner check this out stackoverflow.com/questions/30955639/…
    – parse
    Commented Jan 15, 2021 at 0:13
  • Thanks. I didn't know that. Commented Jan 15, 2021 at 9:44

Not the answer you're looking for? Browse other questions tagged or ask your own question.