Php column name array

Get the column from an array

The reason you are not able to access the value form the array is that the details are stored as object, so you need to use arrow operator ‘->’ to acces the values. So you can try the code as below :

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

When you iterate through $info in $item you have object, not an array. So you need to call it $item->id

if get_sql() accept only one id you need to do something like

but it is always bad idea to query SQL inside the loop. Consider to change your SQL query to something like

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

than you will retrieve all data at once. But if you still want to call function you don’t need two loops. Just do all stuff in one.

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

but note, that rate will be rewritten in each iteration. So you need to collect data to array like $rate[] = get_sql($item->id); or process that data immediately like print it.

to solve your second question i need to know what goes wrong now or any errors you get or what parameters that function expecting.

Assuming that $info is the array mentioned at the beginning, each $item is an object, not an array. So you should try:

You can also use array_map to get the ids:

$idcol = array_map(function($item)id;>,$info); 

Then you can use a foreach loop to send the values to your function (though it would be best if you could make your function work with arrays to avoid multiple queries):

The reason your current loop doesn’t work is because you’re sending the whole array and not using an index like $idcol[i]

array_column — Return the values from a single column in the input array

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

array_column() returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.

 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); ?> 

Get column of last names from recordset, indexed by the «id» column

Источник

array_column

array_column() returns the values from a single column of the array , identified by the column_key . Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array.

Читайте также:  Python функция возвращает индекс

Parameters

A multi-dimensional array or an array of objects from which to pull a column of values from. If an array of objects is provided, then public properties can be directly pulled. In order for protected or private properties to be pulled, the class must implement both the __get() and __isset() magic methods.

The column of values to return. This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an associative array or property name. It may also be null to return complete arrays or objects (this is useful together with index_key to reindex the array).

The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name. The value is cast as usual for array keys (however, prior to PHP 8.0.0, objects supporting conversion to string were also allowed).

Return Values

Returns an array of values representing a single column from the input array.

Changelog

Version Description
8.0.0 Objects in columns indicated by index_key parameter will no longer be cast to string and will now throw a TypeError instead.

Examples

Example #1 Get the column of first names from a recordset

// 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 );
?>

The above example will output:

Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter )

Example #2 Get the column of last names from a recordset, indexed by the «id» column

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

The above example will output:

Array ( [2135] => Doe [3245] => Smith [5342] => Jones [5623] => Doe )

Example #3 Get the column of usernames from the public «username» property of an object

class User
public $username ;

public function __construct ( string $username )
$this -> username = $username ;
>
>

$users = [
new User ( ‘user 1’ ),
new User ( ‘user 2’ ),
new User ( ‘user 3’ ),
];

print_r ( array_column ( $users , ‘username’ ));
?>

The above example will output:

Array ( [0] => user 1 [1] => user 2 [2] => user 3 )

Example #4 Get the column of names from the private «name» property of an object using the magic __get() method.

class Person
private $name ;

public function __construct ( string $name )
$this -> name = $name ;
>

public function __get ( $prop )
return $this -> $prop ;
>

public function __isset ( $prop ) : bool
return isset( $this -> $prop );
>
>

$people = [
new Person ( ‘Fred’ ),
new Person ( ‘Jane’ ),
new Person ( ‘John’ ),
];

print_r ( array_column ( $people , ‘name’ ));
?>

The above example will output:

Array ( [0] => Fred [1] => Jane [2] => John )
  • Array Functions
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

    Request for Comments: array_column

    This RFC proposes a new array function that returns the values of the specified column from a multi-dimensional array. Inspired by database methods like PDOStatement::fetchColumn() , array_column() moves useful functionality into the core that once had to be implemented in userland code with sometimes complex loops.

    This has been submitted as a pull request on GitHub, where there has already been a significant amount of discussion.

    Specification

    Description

    array array_column(array $input, mixed $columnKey[, mixed $indexKey])

    array_column() returns the values from a single column of the input array, identified by the columnKey. Optionally, you may provide an indexKey to index the values in the returned array by the values from the indexKey column in the input array.

    Parameters

    The column of values to return. This value may be the integer key of the column you wish to retrieve, or it may be the string key name for an associative array.

    (Optional.) The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name.

    Return Values

    Returns an array of values representing a single column from the input array.

    Examples

    Example #1: Get column of first names from recordset

     // 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' ) ); $firstNames = array_column($records, 'first_name'); print_r($firstNames);

    The above example will output:

    Array ( [0] => John [1] => Sally [2] => Jane [3] => Peter )

    Example #2: Retrieve a column of values from a numerically-indexed array

     $records = array( array(1, 'John', 'Doe'), array(2, 'Sally', 'Smith'), array(3, 'Jane', 'Jones') ); $lastNames = array_column($records, 2); print_r($lastNames);

    The above example will output:

    Array ( [0] => Doe [1] => Smith [2] => Jones )

    Example #3: Get column of last names from recordset, indexed by the «id» column

    The above example will output:

    Array ( [2135] => Doe [3245] => Smith [5342] => Jones [5623] => Doe )

    Example #4: Mismatched columns

    With array_column() the relationship in finding the values of columnKey to indexKey is much like that of a SQL left join. All values of the columnKey are returned. When a corresponding indexKey cannot be found, the value will be keyed with an integer, starting from zero.

    The following examples will all use the same $mismatchedColumns array defined here:

     $mismatchedColumns = array( array( 'a' => 'foo', 'b' => 'bar', 'e' => 'baz' ), array( 'a' => 'qux', 'c' => 'quux', 'd' => 'corge' ), array( 'a' => 'grault', 'b' => 'garply', 'e' => 'waldo' ), );

    In this example, all rows contain an “a” key, but only two contain a “b” key. If we want to retrieve all “a” values and key them by “b” values, then array_column() behaves like this:

     $foo = array_column($mismatchedColumns, 'a', 'b'); $bar = array('bar' => 'foo', 'qux', 'garply' => 'grault'); /* Both $foo and $bar contain values that look like this: Array ( [bar] => foo [0] => qux [garply] => grault ) */

    However, if we want to retrieve all “b” values and key them by “a” values, we will only have two elements in the resulting array, since only two rows contain “b” values.

    // There is a corresponding "a" value for each "b" value print_r(array_column($mismatchedColumns, 'b', 'a')); /* Array ( [foo] => bar [grault] => garply ) */ // There are no corresponding "c" values for either "b" value print_r(array_column($mismatchedColumns, 'b', 'c')); /* Array ( [0] => bar [1] => garply ) */

    Example #5: indexKey Collisions

    In the event that more than one row contains the same value for indexKey, then the last columnKey value for that indexKey will overwrite the previous value.

    // Using the $records array from Example #1 $firstNames = array_column($records, 'first_name', 'last_name'); print_r($firstNames); /* Array ( [Doe] => Peter [Smith] => Sally [Jones] => Jane ) */

    Proposal and Patch

    The patch (including tests) for this proposal is available in GitHub Pull Request #257.

    Mailing list discussion

    The mailing list discussion is available here.

    Voting

    Voting ends not before Friday, January 18, 2013. The PHP language is not changed, so a 50% + 1 majority is required.

    Источник

    Get MySQL column names in PHP array

    Can someone please help me how to get my MySQL column names out in my while loop? My code goes like this:

    if (mysqli_connect_errno()) < echo "MySQL failed: " . mysqli_connect_errno(); >if (isset($_GET['date'])) < $get_date = $_GET['date']; $result = mysqli_query($conn, "SELECT * FROM stats WHERE form_date = '$get_date'"); $col = array(); while ($row = mysqli_fetch_array($result)) < $col[] = $row['year']; $col[] = $row['month']; $col[] = $row['day']; $col[] = $row['weekday']; $col[] = $row['form_date']; $col[] = $row['name']; $col[] = $row['count']; $col[] = $row['lang']; >echo "
    "; print_r($col); echo "

    "; mysqli_close($conn); > else

    Array ( [0] => 2014 [1] => 01 [2] => 01 [3] => Wednesday [4] => 2014-01-01 [5] => Michael K [6] => 41 [7] => SE [8] => 2014 [9] => 01 [10] => 01 [11] => Wednesday [12] => 2014-01-01 [13] => Nicklas S [14] => 40 [15] => DK [16] => 2014 [17] => 01 [18] => 01 [19] => Wednesday [20] => 2014-01-01 [21] => Jesper S [22] => 5 [23] => SE ) 
    Array ( [year] => 2014 [day] => 01 [month] => 01 [weekday] => Wednesday [form_date] => 2014-01-01 [name] => Michael K [count] => 41 [lang] => SE [year] => 2014 [month] => 01 [day] => 01 [weekday] => Wednesday [form_date] => 2014-01-01 [name] => Nicklas S [count] => 40 [lang] => DK [year] => 2014 [month] => 01 [day] => 01 [weekday] => Wednesday [form_date] => 2014-01-01 [name] => Jesper S [count] => 5 [lang] => SE ) 

    So the keys in my array matches the column names I have in my database. I just can’t seem to wrap my head around how I do this. Can someone help? 🙂

    Источник

Оцените статью