Home > Back-end >  Use Dynamic Array inside Array PHP
Use Dynamic Array inside Array PHP

Time:02-24

I am new in PHP. I am working for send data using PHP API. Its method is like below

$createContact->setCustomFieldValues(
                    [
                       array(
                        'customFieldId' => 'pcVFD6',
                        'value' => array('35')
                        ),
                        array(
                        'customFieldId' => 'pcVnzW',
                        'value' => array('37')
                        )
                    ]
            );

I have data in array like this

$aa = array("pcVFD6"=>"35", "pcVnzW"=>"37");

I want pass this values to above function but I am not getting idea about proper way to do it. I have tried something like this

foreach ($aa as $key => $value){
                
    $createContact->setCustomFieldValues([
        array(
            'customFieldId' => $key,
            'value' => array($value)
            )  
        ]
    );
}

its working but passing only last one array to API. Anyone here can please help me for achieve my goal?

Thanks!

CodePudding user response:

You need to transform the array before you pass it to setCustomFieldValues. You don't want to be calling setCustomFieldValues multiple times as your current attempt does, as that's not equivalent to the original. You just need to change the structure of the array ahead of time.

For example:

$aa = array("pcVFD6"=>"35", "pcVnzW"=>"37");
$transformedArr = array();

foreach ($aa as $key => $value){
  $transformedArr[] = array(
            'customFieldId' => $key,
            'value' => array($value)
            );
}

$createContact->setCustomFieldValues($transformedArr);
  • Related