我有一个从MySQL db中提取的数组,我需要将它重新格式化为另一个数组,而不需要在特定的键上重复。
原始数组:
Array // $categories array
(
[0] => Array
(
[name] => Body & Bath Products
[keyword] => body-and-bath-products
)
[more ...]
)新阵列结构:
Array // $links array
(
[0] => Array
(
[keyword] => Body & Bath Products
[link] => ./Body-and-Bath-Products
[target] => _self
[tooltip] => 1
)
[more ...]
)循环使用PHP:
$links = array();
foreach ($categories as $cat):
if (in_array ($cat['name'], $links)):
continue;
else:
$links[] = array(
'keyword' => $cat['name'],
'link' => './' . $this->url->cap_keyword($cat['keyword']),
'target' => '_self',
'tooltip' => true
);
endif;
endforeach;但这不起作用,我的$links数组中仍有534个条目。
我知道这很简单,但我就是想不起来.
发布于 2013-09-10 00:04:29
您只需使用另一个foreach循环..。
$links = array();
foreach ($categories as $cat){
foreach($links as $value){ // Loop through $links array
if($value['keyword'] == $cat['name']) // Check if $cat['name'] is already in $links
continue 2; // Skip rest of this loop and parent loop if it exists
}
$links[] = array(
'keyword' => $cat['name'],
'link' => './' . $this->url->cap_keyword($cat['keyword']),
'target' => '_self',
'tooltip' => true
);
}发布于 2013-09-09 23:52:44
您的问题是,您正在使用索引键填充$links数组,当您检查该数组中是否存在密钥时,您将使用$cat‘’name‘变量作为键。因为这在$links数组中从未出现过,所以您会得到重复的。
$links = array();
foreach ($categories as $cat):
if (in_array ($cat['name'], $links)): // HERE YOU CHECK IF $links CONTAINS $cat['name'] HOWEVER YOU NEVER STORE $cat['name'] AS KEY
continue;
else:
$links[] = array( // HERE YOU STORE EACH ENTRY WITH KEY AS INDEX FROM 0 TO N
'keyword' => $cat['name'],
'link' => './' . $this->url->cap_keyword($cat['keyword']),
'target' => '_self',
'tooltip' => true
);
endif;
endforeach;解决方案是用$cat‘’name‘而不是索引号来存储密钥。
$links = array();foreach ($categories as $cat):
if (array_key_exists ($cat['name'], $links)):
continue;
else:
$links[$cat['name']] = array( // You should save the entry using $cat['name'] as key for the entry this way when you do the in_array check you can prevent duplicates
'keyword' => $cat['name'],
'link' => './' . $this->url->cap_keyword($cat['keyword']),
'target' => '_self',
'tooltip' => true
);
endif;
endforeach;您需要用键$cat‘’name‘替换数字键,用array_key_exists()方法替换array_key_exists()方法。
in_array()的问题在于它检查顶级数组的值,$links和$links从来不包含$cat‘’name‘作为值,因为它是数组的数组。然而,$links中的数组确实包含$cat‘’name‘。
https://stackoverflow.com/questions/18708709
复制相似问题