我正在尝试构建一个表单,用户从字符串输入数据,表单将根据输入通过json src获取数据子集,并创建一个多维数组并将其保存在数据库中。如果输入先前已添加到数据库,我不希望它再次附加到数组中。
以下是我的代码的外观:
//SET UP the Array
$thisquery_themes[] = array(
strtolower($themename) => array(
"author"=>$data['Author'],
"desc"=>$data['Description'],
"screenshot"=> $screenshot,
"link"=> $data['URI'],
"count"=> 1
)
);
//Get Previously saved data
$existing_themes = get_option('top_themes');
if(!empty($existing_themes)){
foreach ($existing_themes as $group){
foreach(array_keys($group) as $key) {
if($group[strtolower($themename)] == strtolower($themename)){
unset($group[$key][strtolower($themename)]);
}
}
}
$total_themes= array_merge($existing_themes , $thisquery_themes);
update_option('top_themes', $total_themes);
} else {
update_option('top_themes', $thisquery_themes);
}
不是。如果密钥存在于数组中,则数据仍在数组中添加:
Array (
[0] => Array (
[towfiq-i._v5] => Array (
[author] => Towfiq I.
[desc] => Towfiq I. official website.
[count] => 1
)
)
[1] => Array (
[towfiq-i._v5] => Array (
[author] => Towfiq I.
[desc] => Towfiq I. official website.
[count] => 1
)
)
[2] => Array (
[wp-bangla] => Array (
[author] => Ifty Rahman
[desc] => A website template for wpbangla
[count] => 1
)
)
[3] => Array (
[towfiq-i._v5] => Array (
[author] => Towfiq I.
[desc] => Towfiq I. official website.
[count] => 1
)
)
[4] => Array (
[wp-bangla] => Array (
[author] => Ifty Rahman
[desc] => A website template for wpbangla
[count] => 1
)
)
但我希望它是这样的(注意“count”字段值是如何加起来的。让我知道它是否可能):
Array (
[0] => Array (
[towfiq-i._v5] => Array (
[author] => Towfiq I.
[desc] => Towfiq I. official website.
[count] => 3
)
)
[1] => Array (
[wp-bangla] => Array (
[author] => Ifty Rahman
[desc] => A website template for wpbangla
[count] => 2
)
)
非常感谢任何帮助。感谢
答案 0 :(得分:1)
如果只使用一个值,为什么在数组中使用数组呢?除非那是你的结果,否则你的结构很容易看起来像:
Array (
[towfiq-i._v5] => Array (
[author] => Towfiq I.
[desc] => Towfiq I. official website.
[count] => 3
)
[wp-bangla] => Array (
[author] => Ifty Rahman
[desc] => A website template for wpbangla
[count] => 2
)
)
然后你的世界将变得更加容易,因为你可以使用isset($existing_themes[strtolower($themename)])
来检查数组元素是否存在(作为一个例子。)
如果您无法更改收到$existing_themes
的方式,可以重新格式化以下数据:
$existing_themes_mod = array();
foreach ($existing_themes as $t) {
$existing_themes_mod[key($t)] = reset($t);
}
这应该为您提供足够的策略,以便能够对现有条目而不是附件运行“更新”。如果你需要帮助写作,请先告诉我你的尝试。
编辑 - 感谢您粘贴代码。顺便说一下,你应该留意所有的空白......这是实现目标的更好方法
if (!empty($existing_themes)) {
if (isset($existing_themes[strtolower($themename)])) {
if (isset($existing_themes[strtolower($themename)]['count'])) {
$existing_themes[strtolower($themename)]['count'] = $existing_themes[strtolower($themename)]['count'] + 1;
} else {
$existing_themes[strtolower($themename)]['count'] = 1;
}
$thisquery_themes = array();
}
$total_themes= array_merge($existing_themes , $thisquery_themes);
update_option('top_themes', $total_themes);
} else {
update_option('top_themes', $thisquery_themes);
}
您尝试不起作用的原因是当您尝试通过将{1}}递增1来更改$value
时,它不会修改原始数组。当您像这样使用foreach
时,您需要通过引用进行迭代,否则您无法修改该值。你为自己做了太多的工作!