【问题标题】:how to use for loop to save one or more values in a variable form an array ?in codeigniter如何使用for循环将一个或多个值保存在一个变量中,形成一个数组?在codeigniter中
【发布时间】:2015-03-11 06:37:15
【问题描述】:

我有一个数组作为 $result 我从这个选择操作中得到的。我正在使用 codeigniter

$this->db->select('*');
$this->db->from($table);
$this->db->where('User_Id',$User_Id);
$query = $this->db->get();
$results = $query->result();
$result = $results[0];

我想将这些值保存在变量中。我正在做的是

$HeightFrom=$result->HeightFrom;
$HeightTo=$result->HeightTo;
$MaritalStatus=$result->MaritalStatus;
$Religion=$result->Religion;
$MotherTongue=$result->MotherTongue;
$Community=$result->Community;
$ProfileCreatedby=$result->ProfileCreatedby;etc....

但我在 arrary 中有 50 个值。所以想使用 for 循环。我该怎么办?如何编写 for 循环代码。 我的问题是使用 for 循环我想将数组值保存为包含值的变量名

【问题讨论】:

  • 你想做什么??

标签: php arrays codeigniter


【解决方案1】:

您可以同时获取结果并将其分配给变量,如下所示:

while ($result = $query->result()) {

    $HeightFrom=$result->HeightFrom;
    $HeightTo=$result->HeightTo;
    $MaritalStatus=$result->MaritalStatus;
    $Religion=$result->Religion;
    $MotherTongue=$result->MotherTongue;
    $Community=$result->Community;
    $ProfileCreatedby=$result->ProfileCreatedby
}

当没有更多记录可供获取时,它就会停止。

注意:在其当前格式下,它会在循环的每次迭代中覆盖您的变量 - 您必须对其进行处理,例如将其输出或保存在另一个数组中。

【讨论】:

  • :if $result->HeightFrom;is empty 意味着它会显示错误吗?那么有没有其他方法可以找到数组 ['HeightFrom'] 是否存在。如果它存在我应该把它保存在一个变量中
  • 不,在这种情况下它不应该显示错误。它仅将值分配给新变量 - 在本例中为 null、'' 或分配给 $result->HeightFrom 的任何其他值。
  • 如果 $result->HeightFrom ; 不存在那么?所以我只需要自动
  • 那么您的表、字段中可能没有数据或其他问题。试试print_r($query) 看看你的查询是否返回了一些东西。
  • :是的,正确的。所以只有我想把它做成。如果存在,将它保存在变量中,否则不想要。这是我心中的确切问题
【解决方案2】:

这样就可以了:

foreach($result as $key => $value ){
  $$key = $value;
}

$$key 将使用每个键的名称设置变量。例如,如果键是 HeightFrom,则变量将是 $HeightFrom,因此您可以调用这些变量,全部为 50 个。

【讨论】:

    猜你喜欢
    • 2011-05-06
    • 2015-10-20
    • 2022-11-03
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 2021-06-03
    相关资源
    最近更新 更多