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. Commented Jan 14, 2021 at 21:02
  • Assuming $customFields is an array of objects. Commented Jan 14, 2021 at 21:03
  • Oooh I see, first part was just edited in later. Sorry about that Commented Jan 14, 2021 at 21:04
  • @ArSeN I just fixed the formatting, I didn't change it. Commented Jan 14, 2021 at 21:04
  • My bad! @OP - what result are you getting instead of what you are trying to achieve? 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.

Sign up to request clarification or add additional context in comments.

3 Comments

awesome! please consider to mark this question as answered! thanks
Why "it's a good practice to always initialize your variables in PHP"? Is there a specific reason?
@AbsoluteBeginner check this out stackoverflow.com/questions/30955639/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.