我正在尝试数据收集对象,并希望使用类构造来更改传递给新实例化对象的数组的数组键。
主要思想是可以使用数字键传递数组,然后每个数字键将替换为字符串值。该系统基于这样一个事实:数组只是一个数组的数组,每个数组包含三个键/值对。 (参见数据示例)。我知道这是非常脆弱的,我打算接下来解决这个问题。
类别:
class newsCollection {
private $collection;
public function __construct($data)
{
foreach ($data[0] as $key => $value) {
switch ($key) {
case 0:
// Replace key ID with a string ie. 0 with "headline"
break;
case 1:
// Replace key ID with a string ie. 1 with "date"
break;
case 2:
// Replace key ID with a string ie. 2 with "author"
break;
}
}
$this->collection = $data;
}
public function getNewsCollection()
{
return $this->collection;
}
}
数据(数组):
$sports = [
[
"Boston Red Sox vs New York Yankees - 9-3",
"19.06.2017",
"ESPN"
],
[
"Boston Patriot QB breaks new record!",
"16.07.2017",
"NESN"
],
[
"Celtics coach John Doe inducted into hall of fame",
"25.07.2017",
"Fox Sports"
],
[
"Boston Brewins win 16-5 against New York's Rangers",
"21.08.2017",
"NESN"
]
];
期望结果示例:
$sports = [
[
"headline" => Boston Red Sox vs New York Yankees - 9-3",
"date => "19.06.2017",
"author" => "ESPN"
],
ect..
];
最佳答案
您可以使用所需的键创建一个数组
,然后使用array_combine()
将它们设置为输入数组
的键。像这样的事情:
private $keys = [
"headline",
"date",
"author",
];
// ...
public function __construct($data)
{
foreach ($data as &$el) {
$el = array_combine($this->keys, $el);
}
$this->collection = $data;
}
请注意,它是通过引用完成的,因此我们正在修改 foreach
循环内的实际元素。您还应该根据您的需要进行一些验证。
作为旁注,您应该 not do any work in the constructor 。它会给你带来麻烦。最好让另一个函数对您的输入值进行初始工作:
<?php
class newsCollection {
private $collection;
private $keys = [
"headline",
"date",
"author",
];
public function __construct($data)
{
$this->collection = $data;
}
public function assingKeys() {
foreach ($this->collection as &$el) {
$el = array_combine($this->keys, $el);
}
}
public function getNewsCollection()
{
return $this->collection;
}
}
$c = new newsCollection($sports);
$c->assignKeys();
$collection = $c->getNewsCollection();
关于PHP数据收集-使用类构造将数字键替换为字符串ident,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46140347/