数组PHP的键的数组映射

时间:2018-11-08 01:13:25

标签: php

假设我们有以下数据集:

$data = [
  'Newcastle Upon Tyne, Tyne and Wear, England' => 18,
  'Gateshead, Tyne and Wear, England' => 17,
  'Sunderland, Tyne and Wear, England' => 3,
  ...
];

我想通过函数进行映射并更改键,使其看起来像这样:

$data = [
  'Newcastle Upon Tyne' => 18,
  'Gateshead' => 17,
  'Sunderland' => 3,
  ...
];

我以为我可以像这样使用array_walk ...

return array_walk($this->_cities, function(&$key, $val) {
  substr( $key, 0, strpos( $key, ',' ) ) = $b;
});

但这会产生错误:

 Can't use function return value in write context 

所以我是这样做的:

$cleaned_data = [];
foreach ( $this->_cities as $city => $count )
  $cleaned_data[ substr( $city, 0, strpos( $city, ',' ) ) ] = $count;
return $cleaned_data;

是否可以使用array_walk或类似的函数来做到这一点?

2 个答案:

答案 0 :(得分:0)

您可以采用多种方法,一种方法可以使用explode()foreach(),另一种方法可以使用array_walk()。我已经添加了两种使用演示的方式。希望对您有所帮助:)

<?php

$data = [
  'Newcastle Upon Tyne, Tyne and Wear, England' => 18,
  'Gateshead, Tyne and Wear, England' => 17,
  'Sunderland, Tyne and Wear, England' => 3,
];

$result = [];
foreach($data as $key=>$value){
    $result[explode(',',$key)[0]] = $value;
}

print_r($result);

演示: https://3v4l.org/1QQna

使用array_walk()

<?php

$data = [
  'Newcastle Upon Tyne, Tyne and Wear, England' => 18,
  'Gateshead, Tyne and Wear, England' => 17,
  'Sunderland, Tyne and Wear, England' => 3,
];

$result = [];
array_walk($data, function (&$value,$key) use (&$result) {
    $splitted = explode(",",$key);
    $result[ $splitted[0] ] = $value;
});

print_r($result);

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

答案 1 :(得分:0)

我不确定是否可以通过传递引用来使用修改数组键。但是您可以这样:

$data = [
  'Newcastle Upon Tyne, Tyne and Wear, England' => 18,
  'Gateshead, Tyne and Wear, England' => 17,
  'Sunderland, Tyne and Wear, England' => 3,
];
foreach($data as $key => $val) {
  unset($data[$key]);
  $data[substr($key, 0, strpos($key, ',' ))] = $val;
};

echo "<pre>"; print_r($data);