我有多维数组。
从每个子阵列中,我想删除/取消设置价格超过1500的值。
数组
$item = array(
'phone' => array(
array(
'Item' => 'S5',
'info' => array(
array('seller' => 'John', 'price' => 1800),
array('seller' => 'Mason','price' => 1200),
array('seller' => 'Alex','price' => 1500),
),
),
array(
'Item' => 'iPhone 5',
'info' => array(
array('seller' => 'Depay', 'price' => 1900),
array('seller' => 'David', 'price' => 1450),
array('seller' => 'Daemon', 'price' => 1600),
)
),
),
);
我的代码:
foreach($item['phone'] as $key =>$price)
{
foreach($price['info'] as $info => $price2 )
{
if ($info['price'] >= 1500)
{
unset($item[$key][$info ]);
}
}
}
为什么这段代码不起作用?可以这样做吗?如果是的话...怎么???
提前致谢: - )
答案 0 :(得分:1)
您指的是错误的元素级别:
foreach($item['phone'] as $key =>$price)
{
foreach($price['info'] as $info => $price2 ) // $price2
{
if ($info['price'] >= 1500) // should be $price2
{
unset($item[$key][$info ]);
}
}
}
您应该在条件中指向$price2
:
if ($price2['price'] >= 1500) {
然后,在取消设置时,您需要指向/走进指数
// write the complete address of this element you want to unset
unset($item['phone'][$key]['info'][$info]);
// ^ ^ don't forget this since they are part of the structure
总而言之:
foreach($item['phone'] as $key =>$price)
{
foreach($price['info'] as $info => $price2 )
{
if ($price2['price'] >= 1500) {
unset($item['phone'][$key]['info'][$info]);
}
}
}
答案 1 :(得分:0)
您的代码应该像
foreach($item['phone'] as $key => $price) {
foreach($price['info'] as $info => $price2 ) {
if ($price2['price'] >= 1500) {
unset($item['phone'][$key]['info'][$info]);
}
}
}
如果条件是你使用密钥$ info,它应该是$ price2。
以下是正在运行的代码https://ideone.com/Mk7VfU