排列数组

时间:2018-10-16 16:57:47

标签: php arrays sorting

我有一个数组,想以某种格式重新排列。

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"
  ]
]

姓氏和中间名数组在哪里切换位置?谢谢!

4 个答案:

答案 0 :(得分:1)

以这种方式尝试通过简单地按索引{/ {1}}调整/切换数组元素来将 $ existing_array 重新排列为 $ expected_array 格式}}。

$existing_array['Middle Name']

演示: https://3v4l.org/GlqXk

答案 1 :(得分:1)

您可以使用自定义按关键字排序,类似这样。也可以轻松更改和调整。

$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

答案 2 :(得分:0)

您可能想查看本文档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)

希望这会有所帮助!

答案 3 :(得分:0)

<?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)