dtb81443 2015-06-08 20:45
浏览 29
已采纳

在PHP中将未知数转换为数组

I have a query that returns either an object or an array based on the number of items. If there are zero or one items being returned, then it returns the item as an object. If there are two or more items, then it returns an array of objects.

I'm wanting to do a foreach on the query result, but that is throwing an error if it is an object that is returned, rather than an array. So I've created a function that would convert an object to an array.

function to_array($unknown) {
  if (count($unknown) === 0) {
    $array=array($unknown);
  } elseif (!is_array($unknown)) {
    $array = array();
    $array[0] = $unknown;
  } else {
    $array = $unknown;
  }
  return $array;
}

It can be used by simply calling $query_array = to_array($query_return).

Is this be best way to do this? Is there a better way? Might this create any problems?

  • 写回答

2条回答 默认 最新

  • duanlu7680 2015-06-08 21:21
    关注

    I'm wanting to do a foreach on the query result, but that is throwing an error if it is an object that is returned, rather than an array.

    It seems your data source is somewhat unclear or unclean. We are talking about queries, objects and arrays. Who knows what else is possible, the more your data source evolves. Therefore, I would check the data type first and handle all possibilities.

    The gettype function gives you a good starting point. Then you can use a switch to handle all possibilities, even future PHP Modifications as below.

    For the object to array conversion, I would use the get_object_vars function instead of a simple type cast, because it is unclear to me what that type cast really would do. But the get_object_vars function is well documented.

    $type = gettype ( $unknown );
    switch ($type) {
      case "array":
        $array = $unknown;
        break;
      case "object":
        $array = get_object_vars ( $unknown );
        break;
      case "boolean":
      case "integer":
      case "double": 
      case "string":
      case "resource":
      case "NULL":
      case "unknown type":
      default: throw new Exception("Unknown data type");
    }
    
    /* Do something here with $array */
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂