0

I have a function that takes an entry from a textarea, splits it in to lines and makes an array of the data from each line. However, this is a numerical array, and the data needs to have specific keys associated to it.

Is there a function that can insert these keys in to my desired positions, to avoid manually coding each key?

Here is my code, which produces a 4 element array -

function do_split_invitations(){

    /** Split the lines into individual elements in an array */
    $lines = explode("\n", $_POST['invitations']);

    $invites = array(); // Initiate array to avoid errors
    if(!empty($lines)) : foreach($lines as $line) :

            $parts = explode(',', $line); // Split in to parts
            $parts = array_slice($parts, 0, 4); // Take only the first 4 parts (the rest are not needed
            $parts = array_map(array($this, '_clean_callback'), $parts); // Clean the parts

            $invites[] = $parts;

        endforeach;
    endif;

}

Current output (for one line) -

Array
(
    [0] => test@adomain.com
    [1] => John
    [2] => Smith
    [3] => Mr Smith
)

Desired output (for one line) -

Array
(
    ['email'] => test@adomain.com
    ['first_name'] => John
    ['surname'] => Smith
    ['custom'] => Mr Smith
)
4

3 回答 3

2

Array combine is help for you

for eg.

<?php
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);

print_r($c);
?>

Edit

Try in your foreach. i am write a basic structure.

foreach ($Offer as $key => $value) { 
  $offerArray[$key] = $value[4];
}

Output like this format

key => value
key => value
于 2013-07-29T10:58:01.563 回答
2

This will be helpful to you,

$key=array("email","first_name","surname","custom");
$parts = explode(',', $line); 
$parts = array_slice($parts, 0, 4);
$invites[] = array_combine($key,$parts);
于 2013-07-29T12:39:48.827 回答
1

The answer here is to use array_combine($keys, $values);

Note that the function will fail if the number of elements in the $keys and $values array are different.

于 2013-07-29T10:53:06.120 回答