无法从cakephp中的多维数组中删除数组键
I want to delete array index which contain rating 0 here is my array
array(
(int) 0 => array(
'Gig' => array(
'id' => '1',
'rating' => (int) 5
)
),
(int) 1 => array(
'Gig' => array(
'id' => '3',
'rating' => (int) 9
)
),
(int) 2 => array(
'Gig' => array(
'id' => '4',
'rating' => '0'
)
)
)
and what I did
for($i = 0; $i<count($agetGigsItem); $i++)
{
if($agetGigsItem[$i]['Gig']['rating']==0)
{
unset($agetGigsItem[$i]);
}
$this->set('agetGigsItem', $agetGigsItem);
}
i also try foreach loop but unable to resolve this issue.
foreach ($agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] == 0) { unset($agetGigsItem[$key]); }
}
我想删除包含等级0的数组索引这里是我的数组 p>
array(
(int)0 =&gt; array(
'Gig'=&gt; array(
'id'=&gt;'1',
'rating'=&gt;(int) 5
)
),
(int)1 =&gt;数组(
'Gig'=&gt;数组(
'id'=&gt;'3',
'rating'=&gt;( int)9
)
),
(int)2 =&gt;数组(
'Gig'=&gt;数组(
'id'=&gt;'4',
'rating'=&gt; ;'0'
)
)
)
code> pre>
我做了什么 p>
for( $ i = 0; $ i&lt; count($ agetGigsItem); $ i ++)
{
if($ agetGigsItem [$ i] ['Gig'] ['rating'] == 0)
{
unset($ agetGigsItem [$ I]);
}
$ this-&gt; set('agetGigsItem',$ agetGigsItem);
}
code> pre>
我也尝试使用foreach循环但无法解决此问题 问题。 p>
foreach($ agetGigsItem as $ key =&gt; $ value){
if($ value [“Gig”] [“rating”] == 0){unset($ agetGigsItem [$ key]); }
}
code> pre>
div>
I think you need to reupdate your array.
foreach ($agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] != 0)
{
unset($agetGigsItem[$key]);
}
$this->set('agetGigsItem', $agetGigsItem);
}
I hope you are missing $this
and so you cannot access the array in CakePHP.
So try this:
foreach ($this->$agetGigsItem as $key => $value) {
if ($value["Gig"]["rating"] == 0) {
unset($this->$agetGigsItem[$key]);
}
}
This code will unset arrey index with value 0.
<?php
$array=array(
array(
'Gig' => array(
'id' => '1',
'rating' =>5
)
),
array(
'Gig' => array(
'id' => '3',
'rating' =>9
)
),
array(
'Gig' => array(
'id' => '4',
'rating' =>0
)
)
);
foreach($array as $a){
if($a['Gig']['rating']==0){
unset($a['Gig']['rating']);
}
$array1[]=$a;
}
var_dump($array1);
Destroying occurances within an array you are actually processing over with a for
or a foreach
is always a bad idea. Each time you destroy an occurance the loop can easily get corrupted and get in a terrible mess.
If you want to remove items from an array it is better to create a copy of the array and process over that new array in the loop but remove the items from the original array.
So try this instead
$tmparray = $this->agetGigsItem; // will copy agetGigsItem into new array
foreach ($tmparray as $key => $value) {
if ($value["Gig"]["rating"] == 0) {
unset($this->agetGigsItem[$key]);
}
}
unset($tmparray);