从数组中获取列

时间:2013-10-04 04:31:12

标签: php

我是新手,有人能帮助我吗?

我有一个数组

array(2) {
 ["Peter"]=>
  object(stdClass)#504 (2) {
    ["id"]=>
    string(4) "2226"
    ["name"]=>
     string(4) "Peter"
   }
 ["Sam"]=>
  object(stdClass)#505 (2) {
    ["id"]=>
    string(4) "2227"
    ["name"]=>
    string(14) "Sam"
   }
}

我想从列“id”中获取元素,然后将其放入sql中进行循环

$idcol = array()
foreach($info as $item){
$idcol[] = $item['id'];
}

但我不知道为什么我不能获得id列。

对于循环,如何将$ idcol的数组元素放入sql中? get_sql是一个函数

 for($i=0;$i<count($idcol);$i++){
 $rate = get_sql($idcol);
 }

6 个答案:

答案 0 :(得分:2)

您无法从阵列访问值的原因是详细信息存储为对象,因此您需要使用箭头操作符' - &gt;'来访问值。所以你可以尝试下面的代码:

$idcol = array()
foreach($info as $person_details)
{
    $id = $person_details->id;
    $person_name = $person_details->name;
    $idcol[] = $id;
}

答案 1 :(得分:1)

当你在$info中迭代$item时,你有对象,而不是数组。 所以你需要称之为$item->id

如果get_sql()只接受一个I​​D,则需要执行

之类的操作
foreach ($idcol as $id){
    $rate = get_sql($id);
}

但在循环中查询SQL总是坏主意。考虑将您的SQL查询更改为

SELECT * from `table` where `id` IN (1, 2, 3);

比你一次检索所有数据。 但是如果你仍然想要调用函数,则不需要两个循环。只需将所有内容合二为一。

$idcol = array()
foreach($info as $item){
  $rate = get_sql($item->id);
}

但请注意,该费率将在每次迭代中重写。因此,您需要将数据收集到$rate[] = get_sql($item->id);之类的数组,或者立即处理数据,就像打印它一样。

答案 2 :(得分:0)

假设$info是开头提到的数组,每个$item是一个对象,而不是一个数组。所以你应该尝试:

foreach($info as $item){
    $idcol[] = $item->id;
}

答案 3 :(得分:0)

您还可以使用array_map获取ID:

$idcol = array_map(function($item){return $item->id;},$info);

然后你可以使用foreach循环将值发送到你的函数(尽管最好是你可以使你的函数使用数组来避免多次查询):

foreach($idcol as $id){
    $rate = get_sql($id);
}

当前循环不起作用的原因是因为您发送整个数组而不使用像$idcol[i]这样的索引

答案 4 :(得分:-1)

array_column - 返回输入数组

中单个列的值

语法 描述

array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )

array_column()返回数组的单个列中的值,由column_key标识。 (可选)您可以提供index_key,以通过输入数组中index_key列的值索引返回数组中的值。

示例:

<?php
// Array representing a possible record set returned from a database
$records = array(
    array(
        'id' => 2135,
        'first_name' => 'John',
        'last_name' => 'Doe',
    ),
    array(
        'id' => 3245,
        'first_name' => 'Sally',
        'last_name' => 'Smith',
    ),
    array(
        'id' => 5342,
        'first_name' => 'Jane',
        'last_name' => 'Jones',
    ),
    array(
        'id' => 5623,
        'first_name' => 'Peter',
        'last_name' => 'Doe',
    )
);

$first_names = array_column($records, 'first_name');
print_r($first_names);
?>

从记录集中获取姓氏列,由“id”列索引

<?php
// Using the $records array from Example #1
$last_names = array_column($records, 'last_name', 'id');
print_r($last_names);
?>

答案 5 :(得分:-1)

 $idcol = array()
 foreach($info as $item=>$val)
 {
    $idcol[] = $val['id'];
 }