alphy
alphy

Reputation: 291

Exploding array with space as the delimeter and pushing the values to a new array

I have post function that is an array in itself, the post contains full names of people in the form of an array such as:

Array(
  [0] => Adda Gweno
  [1] => Tom malombo
)

I would like to go through this array and explode the values of each key using the space as a delimiter so I can send the individual values to a separate array to be stored separately.

What I have so far:

function save_drs() {    
    $Surname = $this->input->post('Surname'); 
    foreach ($Surname as $e_name):
        $individual = explode(" ", $e_name);
    endforeach;

    $Suggested_Salary = $this->input->post('Suggested_Salary');
    for ($i = 0; $i < count($Surname); $i++) {         
        $bio = array(
            'Surname' =>$individual[0][$i],
            'Other_Names' => $individual[1][$i],
            'Suggested_Salary'=>$Suggested_Salary[$i]
           );
            // $this->db->insert('main_table', $bio);
        print_r($bio);
    }
}

This prints the first letters of the names instead of the words

Array
(   
    [Surname] => A      //Should be Adda
    [Other_Names] => G  //Should be Gweno

)
Array
(   
    [Surname] => T      //Should be Tom
    [Other_Names] => M  //Should be Malombo

)

Suggestions?

Upvotes: 3

Views: 60

Answers (2)

OllyBarca
OllyBarca

Reputation: 1531

Assign to $individual as a multidimensional array:

$individual[] = explode(" ", $e_name);
           ^^

Upvotes: 0

CodeGodie
CodeGodie

Reputation: 12132

You are making it too hard for yourself. This is all you need:

$employees = array("Adda Gweno", "Tom malombo");
$salaries = array("500", "355");
foreach ($employees as $k => $fullname) {
    $names = explode(" ", $fullname);
    $final["Surname"] = $names[0];
    $final["Other_Names"] = $names[1];
    $final["Salaries"] = $salaries[$k];
    var_dump($final);
}

Result:

array (size=3)
  'Surname' => string 'Adda' (length=4)
  'Other_Names' => string 'Gweno' (length=5)
  'Salaries' => string '500' (length=3)
array (size=3)
  'Surname' => string 'Tom' (length=3)
  'Other_Names' => string 'malombo' (length=7)
  'Salaries' => string '355' (length=3)

Upvotes: 1

Related Questions