Jump to content
php.lv forumi

PHP masīva elementu dzēšana un index'u atjaunošana


ArnisR

Recommended Posts

Ir multidimensionālais masīvs:

 

$myArray = array(
array(
 "name" => "Jack"
 "age" => 28
),
array(
 "name" => "Harry"
 "age" => 35
),

array(
 "name" => "Mike"
 "age" => 19
)
);

 

Kā ar PHP izdzēst array elementu pēc name vērtības, pietam atjaunojot visa masīva index'us - 0; 1; 2; 3 utt. ??? Paldies!

Link to comment
Share on other sites

Var kaut kā tā:

http://codepad.org/z8o88yzc

 

$myArray = array(
array(
 "name" => "Jack",
 "age" => 28
),
array(
 "name" => "Harry",
 "age" => 35
),
array(
 "name" => "Mike",
 "age" => 19
)
);
class KeyFilter{
 function __construct($key){
$this->key=$key;
 }
 function byKey($v){
return !($v[$this->key]==$this->val);
 }
 function filter($arr,$val) {
$this->val=$val;
return array_values(array_filter($arr,array($this,"byKey")));
 }
}

var_dump($myArray);
$filter = new KeyFilter("name");
$myArray=$filter->filter($myArray,"Harry");
var_dump($myArray);

Edited by codez
Link to comment
Share on other sites

vienkāršāks variants:

 

http://codepad.org/E78DkzOY

 

<?
$myArray = array(
 array(
"name" => "Jack",
"age" => 28
 ),
 array(
"name" => "Harry",
"age" => 35
 ),
 array(
"name" => "Mike",
"age" => 19
 )
);
function del_by_name($a, $name)
{
 foreach ($a as $k => $v)
 {
if ($v['name'] == $name)
{
 	unset($a[$k]);
 	return array_merge($a);
}
 }
 return $a;
}
var_dump($myArray);
$myArray = del_by_name($myArray, 'Harry');
var_dump($myArray);

?>

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...