nodoze
nodoze

Reputation: 127

PHP - How to switch / reverse values in one column of 2D array

I have an exploded array and I am trying to reverse the first name and last name in a specific column.

Here is the array:

array(729) {
  ["ID;Position;Name;ER;FF;GA"]=>
  array(24) {
    [0]=>
    string(3) "ID"
    [1]=>
    string(3) "Position"
    [2]=>
    string(4) "Name"
    [3]=>
    string(4) "ER"
    [4]=>
    string(6) "FF"
    [5]=>
    string(13) "GA"
  }
  ["7702;Manager;Johnson, Bill;44.5;6T;406"]=>
  array(24) {
    [0]=>
    string(4) "7702"
    [1]=>
    string(1) "Manager"
    [2]=>
    string(11) "Johnson, Bill"
    [3]=>
    string(3) "44.5"
    [4]=>
    string(4) "6T"
    [5]=>
    string(1) "406"
  }

As you can see, I am need to flip the first name and last name in every 3rd element (index[2]). I was thinking to explode every 3rd element via ',' delimiter (since it is always fname, lname) and then use array_reverse to reverse them... and then reconstruct.

$dump_array = explode(PHP_EOL, $dump);

foreach($dump_array as $line){
    $temp[$line]=explode(';', $line);
        }

foreach($temp as $ele){
    var_dump($temp[$ele]);
    $temp[$ele]=array_reverse($temp[$ele[2]]); #I need to do another explode (',') somewhere?
}

Upvotes: 0

Views: 464

Answers (2)

bhushya
bhushya

Reputation: 1317

Here is the another way:

$temp = array("asjd", "first , last", "asdjlakd");

foreach($temp as $ele){
    if (strpos($ele, ",")!== false){
        $data = explode(",", $ele);#I need to do another explode (',') somewhere?
        $reverse_data=array_reverse($data); 
        print_r($reverse_data);
    }
}

Upvotes: 0

Fallen
Fallen

Reputation: 4565

You want to do implode instead of explode() in the last line or a sample demo code below :

foreach($dump as $line) {
    $temp_str = $line[2];
    $temp_str = explode(",", $temp_str);
    $line[2] = $temp_str[1] . ", " . $temp_str[0];
}

How does it work: For every array, it picks that array out as $line and then explode the string stored in $line[2] and reverse their order and replace $line[2] with the new reversed value joined with a comma in middle of them

Upvotes: 1

Related Questions