Chris
Chris

Reputation: 3657

PHP array manipulation, switch values with specific keys - pattern?

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

Upvotes: 2

Views: 92

Answers (1)

Darren
Darren

Reputation: 13128

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

Upvotes: 1

Related Questions