[英]append data in multidimensional array php
我想將表數據導入PHP中的多維數組中,表數據不斷更新,因此,一旦將數據插入表中就必須更新矩陣。 我們如何創建一個多維數組,將數據插入到其中,然后將數據動態附加到數組中?
通常,您從表中得到一個“普通”一維數組。 要從中制作多維數組,您必須將一維數組放入多維數組。
為此,您可以使用以下方法:
$i = 0; //initialize i
while ($i < count($array)) { //as long as i is smaller than the array
foreach ($array as $key => $value) { //walk along the array
$newArray[$i][$key] = $value; // set the multidimensional array
}
$i++; // count one up
}
這樣,您應該獲得一個多維數組,如下所示:
array(
'0' => array(
'0' => 'foo'
'1' => 'bar'
)
'1' => array(
'0' => 'foo'
'1' => 'bar'
)
)
等等...希望這會有所幫助
對於您想做的事情,我認為應該看一下對象方法,因為形成以下注釋
湯姆,方案是我正在為文檔中的術語頻率維護一個表,所以我的column1將是所有文檔中的不同術語,並且為每個新文檔添加一個新列,並插入相應的術語計數,並且如果有任何新任期;
我可以識別以下內容
而不是將文檔設置為null只會更新所需的團隊信息
例
// Porpulate Teams
$teams = array_map(function ($v) {return new Team($v);}, range("A", "Z"));
// Porpulate Documents
$doc = new SplObjectStorage();
for($i = 0; $i < 100; $i ++) {
$doc->attach(new Document($teams[array_rand($teams)]));
}
usort($teams, function($a,$b){ return $b->frequency - $a->frequency;});
//Top 10 Teams
echo "<pre>";
foreach (array_slice($teams, 0,10) as $team ) {
echo "Team ", $team->name, "\t", $team->frequency, PHP_EOL;
}
輸出量
Team P 9
Team N 8
Team S 7
Team Q 6
Team M 6
Team D 6
Team O 5
Team G 5
Team K 5
Team F 5
使用的類
class Document {
function __construct(Team &$team) {
//Do your metrix
$team->frequency ++;
}
}
class Team {
public $name;
public $frequency = 0;
function __construct($name) {
$this->name = $name;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.