2

I've got array data which outputs as:

'TextField3283' => string 'A'
'TextField3287' => string 'B'
'TextField3288' => string 'C'
'Custom_TextField3283' => string 'customfield_10202'
'Custom_TextField3287' => string 'customfield_10216'
'Custom_TextField3288' => string 'customfield_10212'

What I need to do is shuffle the key and values to create the following output:

'customfield_10202' => 'A'
'customfield_10216' => 'B'
'customfield_10212' => 'C'

So the value of the last three entries become the keys of a new array, with the correct values. As you can see, the last three entries are the same as the first three but prefixed with Custom_

With this in mind, I've attempted to use:

$customfields = array();

foreach ($data as $key => $value) {

    if (preg_match("/_TextField/", $key)) {
        array_push($customfields, array($value => $key));
    }
}

Which outputs:

'customfield_10202' => 'Custom_TextField3283'
'customfield_10216' => 'Custom_TextField3287'
'customfield_10212' => 'Custom_TextField3288' 

But now I'm not sure the best way to lookup the values as keys in the first array and return their values...

I hope this makes sense

1
  • 1. Create 2 arrays: of text fields and custom text fields with numeric keys like 3283. 2. merge them (after you have pre-processed separated arrays this step is trivial) Commented Aug 7, 2015 at 2:45

1 Answer 1

1

You were very close with your attempt. Provided your array stays as it is, all you need to do is this:

foreach ($array as $key => $value) {

    if (preg_match("/_TextField/", $key)) {
        list($unused, $findkey) = explode("_", $key);
        array_push($customfields, array($value => $array[$findkey]));
    }
}

Notice how we explode() on the _? That's because the key for the value is set as an array index.

Example

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

1 Comment

Perfect, exactly what I was after. Yeah I'd worked out the explode after posting, just not the rest. Thank you very much.

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.