将PHP数组$ key => $ value转换为$ value =>下一个$ value

时间:2019-08-12 21:27:15

标签: php arrays

我真的不知道如何表达问题,所以我只写代码。

我希望能够转换此数组:

Array
(
    [SELECT0] => 'orange'
    [INPUT0] => '100'
    [SELECT1] => 'bannana'
    [INPUT1] => '200'
    [SELECT2] => 'apple'
    [INPUT2] => '300'
)

进入此数组:

Array
(
    [orange] => '100'
    [bannana] => '200'
    [apple] => '300'
)

*如果您知道如何正确表达该问题,请编辑此问题标题:)

我的实际数组是:

array(12) {
  ["SELECT0"]=>
  string(3) "000"
  ["INPUT0"]=>
  string(2) "50"
  ["SELECT1"]=>
  string(3) "000"
  ["INPUT1"]=>
  string(3) "150"
  ["SELECT2"]=>
  string(4) "5260"
  ["INPUT2"]=>
  string(3) "200"
  ["SELECT3"]=>
  string(4) "5261"
  ["INPUT3"]=>
  string(3) "300"
  ["SELECT4"]=>
  string(3) "000"
  ["INPUT4"]=>
  string(3) "400"
  ["SELECT5"]=>
  string(4) "5262"
  ["INPUT5"]=>
  string(3) "500"
}

3 个答案:

答案 0 :(得分:2)

这是组合三个PHP数组函数的一种方法:

$result = array_combine(...array_map(null, ...array_chunk($array, 2)));

array_chunk给您

[
    ['orange', '100'],
    ['banana', '200'],
    ['apple', '300']
];

array_map将其转换为:

[
    ['orange', 'banana', 'apple'],
    ['100', '200', '300'],
];

可以直接输入array_column

答案 1 :(得分:1)

您需要做的就是遍历所有数组值,然后将每个奇数作为键,将下一个索引作为值。

List<WebElement> rows = driver.findElements(By.cssSelector(".datagrid-btable tr.datagrid-row"));
System.out.println(rows.size());

List<WebElement> filteredRows = rows.stream().filter(element ->
        element.findElement(By.cssSelector("td[field='PLANT_NM'")).getText().equals("BOCAR LERMA"))
        .collect(Collectors.toList());

Assert.assertTrue(filteredRows.size() > 0, "Row with \"BOCAR LERMA\" PLANT_NM exist.");
filteredRows.get(0).click();

现在$arr = [ 'SELECT0' => 'orange', 'INPUT0' => '100', 'SELECT1' => 'bannana', 'INPUT1' => '200', 'SELECT2' => 'apple', 'INPUT2' => '300' ]; $arr = array_values($arr); $newData = []; for ($i = 0; $i < count($arr); $i++) { $newData[$arr[$i]] = $arr[++$i]; } 包含以下内容:

$newData

答案 2 :(得分:1)

假设格式永远不会改变...

$new=array();//start a new array
$count=count($array)/2; //get the number of items to loop through


for ($i = 0; $i < $count; $i++) { //loop

$k='SELECT'.$i; //key
$v='INPUT'.$i; //value

$new[$array[$k]]=$array[$v]; //create new array

}

print_r($new); //display