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.
如您所见,我需要在每个第3个元素(index [2])中翻转名字和姓氏。我想通过','分隔符(因为它始终是fname,lname)来爆炸每个第3个元素,然后使用array_reverse来反转它们......然后重构。
$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 个解决方案
#1
1
You want to do implode
instead of explode()
in the last line or a sample demo code below :
你想在最后一行或下面的示例演示代码中进行implode而不是explode():
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
它是如何工作的:对于每个数组,它将该数组作为$ line选择,然后爆炸存储在$ line [2]中的字符串并反转它们的顺序并用新的反转值替换$ line [2]并用逗号连接他们中间
#2
0
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);
}
}
#1
1
You want to do implode
instead of explode()
in the last line or a sample demo code below :
你想在最后一行或下面的示例演示代码中进行implode而不是explode():
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
它是如何工作的:对于每个数组,它将该数组作为$ line选择,然后爆炸存储在$ line [2]中的字符串并反转它们的顺序并用新的反转值替换$ line [2]并用逗号连接他们中间
#2
0
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);
}
}