我有一个数组,我想以某种格式重新排列。
array:4 [▼
"ROWID" => array:3 [▼
0 => 0
1 => 1
2 => 2
]
"First Name" => array:3 [▼
0 => "BILLY"
1 => "SALLY"
2 => "TYLER"
]
"Last Name" => array:3 [▼
0 => "RAY"
1 => "SUE"
2 => "TERRIER"
]
"Middle Name" => array:3 [▼
0 => "B."
1 => "S."
2 => "T."
]
]
如何排列数组,使其看起来像这样:
array:4 [▼
"ROWID" => array:3 [▼
0 => 0
1 => 1
2 => 2
]
"First Name" => array:3 [▼
0 => "BILLY"
1 => "SALLY"
2 => "TYLER"
]
"Middle Name" => array:3 [▼
0 => "B."
1 => "S."
2 => "T."
]
"Last Name" => array:3 [▼
0 => "RAY"
1 => "SUE"
2 => "TERRIER"
]
]
姓氏和中间名数组在哪里交换位置?
尝试通过像$existing_array['Middle Name']
和$existing_array['Last Name']
这样的索引简单调整/切换数组元素,将
$existing_array重新排列为
$expected_array格式。
<?php
$existing_array = ["ROWID" =>[0 => 0,1 => 1,2 => 2],
"First Name" => [0 => "BILLY",1 => "SALLY",2 => "TYLER"],
"Last Name" => [0 => "RAY",1 => "SUE",2 => "TERRIER"],
"Middle Name" =>[0 => "B.",1 => "S.",2 => "T."]];
$expected_array = ['ROWID'=>$existing_array['ROWID'],'First Name'=>$existing_array['First Name'],'Middle Name'=>$existing_array['Middle Name'],'Last Name'=>$existing_array['Last Name']];
print_r($expected_array);
您可以使用自定义按键排序,如下所示。它还可以轻松更改和调整。
$ranking = array(
'ROWID',
'First Name',
'Middle Name',
'Last Name'
);
uksort( $name, function ( $a, $b ) use ( $ranking ) {
return array_search ( $a, $ranking ) < array_search ( $b, $ranking ) ? -1 : 1;
} );
这是演示:DEMO
您可能想查看此文档http://php.net/manual/en/function.array-replace.php
使用 php 中的数组替换功能,您可以使用键交换数组的值,例如
$array = ["a","b","c"];
$change1 = array(0 => "d");
$try = array_replace($array,$change1);
//expected result
$array = ["a","b","d"];
就你而言,
$array = ["ROWID[]", "First Name[]", "Last Name[]", "Middle Name[]"]
$change1 = array(2 => Middle Name[], 3 => Last Name[])
$result = array_replace($array,$change1)
希望对你有帮助!
<?php
$arr = array(
"ROWID" => array(
0 => 0,
1 => 1,
2 => 2
),
"First Name" => array(
0 => "BILLY",
1 => "SALLY",
2 => "TYLER"
),
"Last Name" => array(
0 => "RAY",
1 => "SUE",
2 => "TERRIER"
),
"Middle Name" => array(
0 => "B.",
1 => "S.",
2 => "T."
)
);
foreach ($arr as $key => $value) {
if ($key == 'Last Name') {
$temp = $arr[$key];
unset($arr[$key]);
$arr['Last Name'] = $temp;
}
}
var_dump($arr);
输出:
array (size=4)
'ROWID' =>
array (size=3)
0 => int 0
1 => int 1
2 => int 2
'First Name' =>
array (size=3)
0 => string 'BILLY' (length=5)
1 => string 'SALLY' (length=5)
2 => string 'TYLER' (length=5)
'Middle Name' =>
array (size=3)
0 => string 'B.' (length=2)
1 => string 'S.' (length=2)
2 => string 'T.' (length=2)
'Last Name' =>
array (size=3)
0 => string 'RAY' (length=3)
1 => string 'SUE' (length=3)
2 => string 'TERRIER' (length=7)