dou7851 2014-11-02 21:55
浏览 159
已采纳

Foreach只返回一个输出

Okay so I am stuck here and I know there would be a simple solution, but I can't figure it out. So the thing is that I have a function which creates columns in a database if not exists. I got the function to work but I want to add the functionality in the function of detecting the column type (VARCHAR, INT etc) and creating columns accordingly. I am trying to get this done by gettype keyword. Now, $productData is in array so I need to apply foreach to get them separated and then I get the value type, the problem is that in the end foreach loop, it gives me only string. Where $productData has 4 strings and 1 integer ..

$array       = (array) $productData;
$arrayValues = array_values( $array );
$i = 0;

foreach ( $arrayValues as $key => $value ) {
    $types = array( "id-$i" => gettype( $value ) );
    $i++;
}
var_dump($types);

Can somebody help me out there please?

Thanks ..

  • 写回答

2条回答 默认 最新

  • douaikuai2715 2014-11-02 22:00
    关注

    You need to initialise the array only once and add elements to it later:

    $array       = (array) $productData;
    $arrayValues = array_values( $array );
    $i = 0;
    
    $types = array();
    foreach ($arrayValues as $key => $value) {
        $types["id-$i"] = gettype($value);
        $i++;
    }
    var_dump($types);
    

    Be careful with gettype() as it will fail on bojects. You need to make sure that each $value is an internal type

    Update: The gettype() will return "object" for all objects. So it is a safe way to determine the type of a variable. Although in case you need the class of the object you need to use get_class() in case gettype() returns "object"

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测