繁体   English   中英

PHP:帮助数组结构

[英]PHP: help with array structure

我的最后一个问题帮助我将数据从表单获取到数组中。 该数组的结构与我以前使用的任何东西都大不相同。 我有多个记录,每个记录都有一个文本框和一个复选框。 这是表格数据:

array(4) { 
["product"]=> array(4) { 
    [0]=> string(5) "Dummy" 
    [1]=> string(7) "Dummy 2" 
    [2]=> string(7) "Dummy 3" 
    [3]=> string(7) "Dummy 4" 
} 
["tags"]=> array(4) { 
    [0]=> string(25) "#enter, #product, #hastag" 
    [1]=> string(0) "" 
    [2]=> string(25) "#enter, #product, #hastag" 
    [3]=> string(25) "#enter, #product, #hastag" 
} 
["chk"]=> array(2) { 
    [0]=> string(2) "on" 
    [2]=> string(2) "on" 
} 
["submit"]=> string(5) "tweet" 

} 

我想将数据从此数组转换为(仅当chk =“ on”时)形式:

tweet[0]["product"] = "dummy"
tweet[0]["tag"] = "hash tag list here"

tweet[1]["product"] = "dummy3"
tweet[1]["tag"] = "hash tag list here"

任何帮助,不胜感激! :)

首先,我建议使用1而不是on 您应该尽可能使用数值,因为它们需要较少的处理。 我认为您需要重新调整HTML,因此您根本不需要在PHP方面进行任何处理...

<input type="checkbox" name="tweet[(YOUR_TWEET_ID)][product]" value="PRODUCT_NAME"/>
<input type="text" name="tweet[(YOUR_TWEET_ID)][tags]" value=""/>

这将使表单完全按照您的需要$ _POST,而无需任何其他代码。

更新

foreach ($_POST['tweet'] as $tweetId => $value) {
   //again, it'd be a good idea to use a numerical value here
   if (strlen($value['product']) > 0) {
      //this tweet was checked, lets do with it what we need

      //here's how you'd get the tags
      echo $_POST['tweet'][$tweetId]['tags'];
   }
}
$finalArray = array();
foreach($array['product'] as $key => $name){
    if(!empty($array['chk'][$key])){
        $finalArray[] = array(
            "product" => $name,
            "tag" => $array['tags'][$key]);
    };
}

很简单:

$i=0;
foreach ($array['chk'] as $key => $val) {
     if ($val == "on") {
         $new_array[$i]['product'] = $array['product'][$key]; 
         $new_array[$i++]['tags'] = $array['tags'][$key];
     }
}

print_r($new_array);

应该这样做,还有其他方法,这只是其中之一。

foreach ($records['chk'] as $id => $temp) {
  $tweet[$id]['product'] = $records['product'][$id];
  $tweet[$id]['tag'] = $records['tags'][$id];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM