2 Strings into key/value array help!

General discussions related to php

Moderators: gesf, Michalio

Post Reply
jamiesw

Hi there,
I have 2 strings that I pull from WordPress/gravity forms.

What i want to do is merge these 2 fields together to create a key/value pair in an array that i can then loop through later.
My data looks something like this but with more items.
strData = "jamie,smith,2003-12-23,male, 2 My Street, MyTown,MyCounty,EH12 3RE,1234,more strings";
strFields = "firstname,lastname,DoB,gender,address1,town,county,postcode,clientid,otherdata";

thanks
simonbrahan

You need to split your fields and data, trim any erroneous whitespace, then combine the fields and data into your structure. The code below shows how it goes together:

Code: Select all

$strData = "jamie,smith,2003-12-23,male, 2 My Street, MyTown,MyCounty,EH12 3RE,1234,more strings";
$strFields = "firstname,lastname,DoB,gender,address1,town,county,postcode,clientid,otherdata";

$data = array_map('trim', explode(',', $strData));
$fields = array_map('trim', explode(',', $strFields));

$user = array_combine($fields, $data);
Note that this data structure is pretty fragile: if you add any new fields, your user data will be out of sync. What functions in gravity forms are you using to store data this way? There might be a better way to do it.
jamiesw

thanks for the quick reply.

We are getting the data via zapier from Rezdy(Online booking system for tours/holidays) 2 of the fields outputs from zapier as the comma separated values as shown, those to fields - data and fieldname always match up. these 2 values are stored in fields in a gravity form.
So with your code so far we have:

Code: Select all

add_action( 'gform_after_submission_1', 'splitZapierIncoming', 10, 2 );

function splitZapierIncoming($entry, $form){

    $strData = rgar( $entry, '5' );
    $strFields = rgar($entry, '8');
	$data = array_map('trim', explode(',', $strData));
	$fields = array_map('trim', explode(',', $strFields));
	
	$user = array_combine($fields, $data);

    $json = json_encode($user);
    $my_post = array(
        'post_title'    => wp_strip_all_tags( rgar($entry, '9') ),
        'post_content'  => $json,
        'post_status'   => 'publish',
        'post_author'   => 1,
        'post_category' => array( 8,39 )
      );
       
      // Insert the post into the database
      wp_insert_post( $my_post );

}
The ultimate aim is not to output to a wp post but it at least see the data being transformed as it comes in,
We will be either putting it back into another form in gravity or pushing it to a different database.
simonbrahan

Looks like you've got it covered then.
Post Reply