如果满足某些条件,我试图从多维数组中删除记录。条件是元素'cap'应该只有'Capped'或Uncapped',如果'Other'存在,它应该从数组中删除。
我尝试过使用Unset()但没有运气。它不会破坏代码,但它不会改变任何东西。数组的输出:
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="container">
<div class="m-col-6">
<ul data-bind="foreach: products">
<li data-bind="template: 'productTemplate'"></li>
</ul>
</div>
</div>
<hr />
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
<script type="text/html" id="productTemplate">
<h1 data-bind="text: title"></h1>
<p data-bind="text: id"></p>
<div data-bind="with: newItem">
<input type="checkbox" data-bind="checked: productClip" />
<label>has pump clips</label>
<input type="number" data-bind="value: productQty" />
<button data-bind="click: $parent.addItem">add to list</button>
</div>
<ul data-bind="foreach: items">
<li>
<!-- ko template: 'itemsTemplate' --><!-- /ko -->
<button data-bind="click: $parent.removeItem">Remove</button>
</li>
</ul>
</script>
<script type="text/html" id="itemsTemplate">
<b data-bind="text: $parent.title"></b>
<span data-bind="text: productClip() ? 'has' : 'does not have'"></span> pump clips
(<span data-bind="text: productQty"></span>)
</script>
删除“其他”记录的代码:
[0] => Array
(
[name] => Club Name
[speed] => Annual Membership
[cap] => Other
[s_description] => Short description
[l_description] => Long description
)
[1] => Array
(
[name] => 50\5Mbps Fibre with 250GB
[speed] => Residential 50/5 Capped
[cap] => Capped
[s_description] => Short description
[l_description] => Long description
)
[2] => Array
(
[name] => FB-FP-B-V-50/5MBPS-400-24
[speed] => Residential 50/5 Capped
[cap] => Capped
[s_description] => Short description
[l_description] => Long description
)
我意识到我可能会做一些非常愚蠢的事情,但对于一些应该相当简单的事情,这似乎真的很难!
由于
答案 0 :(得分:1)
假设您的主数组存储在变量:$ product_details
下您的代码将是
foreach($product_details as $key => $product){
if($product['cap'] == "Other"){
unset($product_details[$key]);
}
}
你不能循环'$ product_details ['cap']',因为那是你内部数组的一部分。 您必须遍历外部数组,然后检查内部数组的值。
我希望这是有道理的。
编辑:在重新阅读您的问题时,您可以将if语句更改为此以使其更加开放;
if($product['cap'] != "Capped" && $product['cap'] != "Uncapped"){
答案 1 :(得分:1)
我的解决方案
foreach ($your_array as $element) {
if ($element['cap'] == "Other") {
continue;
} else {
$newarray[] = $element;
}
}
答案 2 :(得分:1)
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$a2=array("e"=>"red","f"=>"green","g"=>"blue");
$result=array_diff($a1,$a2);
否则你必须像上面那样循环。还有其他方法可以映射。