简体   繁体   中英

How insert associative array inside another array? PHP

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM