我试图在对象中找到一个值,但我似乎无法得到正在做的事情。也许我错了。我有两个对象,我想要做的是删除不在第二个对象中的行。 这是对象1:
Array (
[idCategory1] => 1
[idCategory2] => 2
[idCategory4] => 4
)
这是对象2:
Array (
[0] => Array (
[CategoriesProvider] => Array (
[id] => 28
[provider_id] => 2
[category_id] => 1
[created] => 2015-03-13 20:25:17
[modified] => 2015-03-13 20:25:17
)
)
[1] => Array (
[CategoriesProvider] => Array (
[id] => 29
[provider_id] => 2
[category_id] => 2
[created] => 2015-03-13 20:25:17
[modified] => 2015-03-13 20:25:17
)
)
[2] => Array (
[CategoriesProvider] => Array (
[id] => 30
[provider_id] => 2
[category_id] => 4
[created] => 2015-03-13 20:25:17
[modified] => 2015-03-13 20:25:17
)
)
)
这是我删除对象2中不在对象1中的行的代码。
foreach ($CategoriesOfProvider as $key ) {
if(isset($CategoriesProvider['CategoriesProvider']->$key['CategoriesProvider']['category_id'])) {
} else {
$this->User->Provider->CategoriesProvider->id = $key['CategoriesProvider']['id'];
//$this->request->allowMethod('post', 'delete');
if ($this->User->Provider->CategoriesProvider->delete()) {
} else {
$this->Session->setFlash(
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> No se pudo borrar la relacion producto - categoría.',
'default',
array('class' => 'alert alert-danger alert-dismissible', 'type' => 'alert')
);
}
}
}
$CategoriesOfProvider
是对象2而$CategoriesProvider
是对象1.所以我试图使用isset来查找对象2中的id是否在对象1的值中。我认为我使用isset错误。或者还有另一种方式吗?我想也许可以针对对象1的每个值运行它。这会更好吗?
提前感谢您的帮助。
答案 0 :(得分:0)
好的,我发现了怎么做。我停止使用isset而是使用另一个foreach并浏览对象1中的所有值。如果找不到,那么我删除了额外的类别。这是代码。
$this->User->Provider->CategoriesProvider->recursive = -1;
$CategoriesOfProvider = $this->User->Provider->CategoriesProvider->find('all', array( 'conditions'=> array('CategoriesProvider.provider_id' => $provider_id ) ) );
//echo print_r($CategoriesProvider);
//return print_r($CategoriesOfProvider);
foreach ($CategoriesOfProvider as $key ) {
$found = false;
//if(isset($CategoriesProvider['CategoriesProvider']->$key['CategoriesProvider']['category_id'])) {
foreach ($CategoriesProvider as $key1 => $value) {
if($key['CategoriesProvider']['category_id'] == $value) {
$found = true;
}
}
if($found) {
} else {
$this->User->Provider->CategoriesProvider->id = $key['CategoriesProvider']['id'];
//$this->request->allowMethod('post', 'delete');
if ($this->User->Provider->CategoriesProvider->delete()) {
} else {
$this->Session->setFlash(
'<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> No se pudo borrar la relacion producto - categoría.',
'default',
array('class' => 'alert alert-danger alert-dismissible', 'type' => 'alert')
);
}
}
}
我希望它有助于某人:P