dongle7882
2014-08-03 19:43 阅读 62
已采纳

PHP - 如何在一列2D数组中切换/反转值

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?
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    dongtang5229 dongtang5229 2014-08-03 19:47

    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

    点赞 评论 复制链接分享
  • duanbu4962 duanbu4962 2014-08-03 19:58

    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);
        }
    }
    
    点赞 评论 复制链接分享

相关推荐