我必须在PHP中扁平化多维表以获得以下函数,以使它们更具可读性。另外,这个脚本的效果需要一点时间。以下是应该运行的代码:
$data = array(
"one" => "one",
"two" => array(
"three" => "three",
"four" => "four",
),
"five" => "five",
"six" => array(
"seven" => "seven",
"eight" => array(
"nine" => "nine",
"ten" => "ten"
)
)
);
$flat=array();
do{
$newFlat=array();
if(empty($data)) break;
if(empty($flat)) $flat = $data;
$findArray = FALSE;
foreach($flat as $key => $value){
if(is_array($value)){
if(is_string($key)) $newFlat[] = 'Start'.$key;
foreach($value as $keySec => $valueSec){
if(is_array($valueSec)){
if(is_string($keySec)) $newFlat[] = 'Start'.$keySec;
$newFlat[] = $valueSec;
if(is_string($keySec)) $newFlat[] = 'End'.$keySec;
$findArray = TRUE;
}else{
$newFlat[$keySec] = $value;
}
}
if(is_string($key)) $newFlat[] = 'End'.$key;
}else{
$newFlat[$key] = $value;
}
}
$flat = $newFlat;
}while($findArray);
print_r($flat);
结果是$持平。可能知道如何转换这个脚本以减少时间和更少的内存?我希望结果看起来像这样:
/*
Result $flat looking like it:
$flat = [
'one' => 'one',
1 => 'Starttwo',
'three' => 'three',
'four' => 'four',
4 => 'Endtwo',
'five' => 'five,
6 => 'StartSix',
'seven' => 'seven',
8 => 'Starteight',
'nine' => 'nine',
'ten' => 'ten',
11 => 'Endeight',
12 => 'EndSix'
];
*/
聚苯乙烯。抱歉我的应受谴责的英语。我想,尽管如此,你会理解我的。
答案 0 :(得分:0)
<强>尝试:强>
class array_class
{
public $data = array();
public $new_array = array();
public $value = 1;
public $number = "";
public function __construct($data)
{
$this->data = $data;
$this->flatten_array($this->data);
}
private function flatten_array($array)
{
foreach($array as $key => $value)
{
if(is_array($value))
{
$this->number = $key;
$this->new_array[$this->value++] = "Start" . $key;
$this->flatten_array($value);
}
else
{
$this->new_array[$key] = $value;
$this->value++;
}
}
$this->new_array[$this->value] = "End" . $this->number;
}
}
<强>输出:强>
Array ( [one] => one [2] => Starttwo [three] => three [four] => four [5] => Endtwo [five] => five [6] => Startsix [seven] => seven [8] => Starteight [nine] => nine [ten] => ten [11] => Endeight )
答案 1 :(得分:0)
试试这个:
function flatten_array($data) {
$newArray = array();
foreach ($data as $key => $value) {
if (is_array($value)) {
$newArray[] = 'Start' . $key;
$newArray = array_merge($newArray,flatten_array($value));
$newArray[] = 'End' . $key;
} else {
$newArray[$key] = $value;
}
}
return $newArray;
}
$flat = flatten_array($data);
print_r($flat);
输出:
Array
(
[one] => one
[0] => Starttwo
[three] => three
[four] => four
[1] => Endtwo
[five] => five
[2] => Startsix
[seven] => seven
[3] => Starteight
[nine] => nine
[ten] => ten
[4] => Endeight
[5] => Endsix
)