這是我的地圖類:PHP映射鍵(數組)通過數字刪除不起作用?
/**
* Map
*
* Collection of items, with a key.
* @Author Jony <[email protected]>
*/
Class Map
{
/**
* Annonymous Constructor
* Sets up the array.
*/
function __construct()
{
$this->map = array();
}
/**
* Method add
* Adds a new item to the collection with a key.
*
* Note: Key can NOT be numeric!
*
* @param key The key of the item.
* @param value The value of the item.
* @return void
*/
public function add($key, $value)
{
$this->map[$key] = $value;
}
/**
* Contains
* Checks if an item with specific key exists.
*
* @param key The key.
* @return Boolean
*/
public function contains($key)
{
if (!is_numeric($key))
{
return (isset($this->map[$key])) ? true : false;
}
else
{
$values = array_values($this->map);
return (isset($values[$key])) ? true : false;
}
}
/**
* Method remove
* Removes an item from the collection by key.
*
* @param key The key of the item.
* @return void
*/
public function remove($key)
{
if (!is_numeric($key))
{
if (isset($this->map[$key]))
unset($this->map[$key]);
}
else
{
$values = array_values($this->map);
if (isset($values[$key]))
{
unset($values[$key]);
}
}
}
/**
* Method get
* Gets an item from the collection by key.
*
* Note: If entered numeric, it will get the key
* by it's offset position number. Arrays starting from 0.
*
* @param key The key of the item
* @return Array item value (Either String, Integer, Object).
*/
public function get($key)
{
if (!is_numeric($key))
{
return (isset($this->map[$key])) ? $this->map[$key] : null;
}
else
{
$values = array_values($this->map);
return (isset($values[$key])) ? $values[$key] : null;
}
}
}
我想創建自己的地圖類型數組類(從Java)只是爲了實踐和使用的時候。
現在我遇到了包含/刪除方法的問題。
當我不使用數字刪除/包含它工作一切正常,誤差主要是與刪除。
當我刪除的偏移量(數字)的項目,我不認爲它會從實際的數組中刪除。
好的,現在讓我們調試它並測試。
$d = new Map();
$d->add("heyy", 55);
$d->remove(0);
if ($d->contains(0))
{
echo 5555;
}
創建新的地圖對象,添加新值,去除偏移0,檢查是否存在如果是echo 5555
。
現在,讓我們做的var_dump($值[$關鍵]);刪除後:
結果:NULL
之前將其刪除:結果
:55
現在讓我們來呼應$這個 - >地圖( 「heyy」)後刪除:
結果:55
好吧,現在這意味着該項目不會從陣列本身中刪除。
我已經試過:
$values = array_values($this->map);
if (isset($this->map[$values[$key]]))
{
unset($this->map[$values[$key]]);
}
還不行。
有什麼不對呢?
@rid在我試圖消除的從陣列的偏移值的代碼的最後,我甚至試圖做它是這樣的字符串:「」。$ values [$ key]。「」 –
不,0表示偏移0,array_values通過偏移量獲取數組項的值。所以$ values [0] = $ this-> map [「heyy」] –
array_values創建一個新數組 - 因此map字段仍然包含key 0。 – madflow