zahir hussain
zahir hussain

Reputation: 3739

get particular column value

i want take the particular column all value in multidimensional array...

i need to get the value of or column ("rose","daisy","orchid")...

how do get?

is there any predefined function? because in my array have 1000 record, so loop will continue to run 1000 times, program will slow, so...

Upvotes: 1

Views: 214

Answers (3)

thara
thara

Reputation: 39

In PHP, the array_column() function is specifically designed to extract a single column's values from a multidimensional array. It is highly optimized and faster than manually looping through arrays, even for large datasets. Example Use Case

If your array looks like this:

$array = [
    ['id' => 1, 'type' => 'rose', 'color' => 'red'],
    ['id' => 2, 'type' => 'daisy', 'color' => 'yellow'],
    ['id' => 3, 'type' => 'orchid', 'color' => 'purple'],
    // ... up to 1000 records
];

$flowers = array_column($array, 'flower');

print_r($flowers);

Output:

Array
(
    [0] => rose
    [1] => daisy
    [2] => orchid
)

Upvotes: 0

muruga
muruga

Reputation: 2122

<?php
$shop = array( array("rose", 1.25 , 15),
               array("daisy", 0.75 , 25),
               array("orchid", 1.15 , 7)
          );

echo $shop[0][0]." costs ".$shop[0][1]." and you get ".$shop[0][2]."\n";
echo $shop[1][0]." costs ".$shop[1][1]." and you get ".$shop[1][2]."\n";
echo $shop[2][0]." costs ".$shop[2][1]." and you get ".$shop[2][2]."\n";

?>

Upvotes: 0

Lotus Notes
Lotus Notes

Reputation: 6363

Iterate through each array in the array, choosing only one key (Sorry if that sounds a bit confusing, here's what I mean):

$flowers = array();
$flowers[] = array('type'=>'rose', 'color'=>'red');
$flowers[] = array('type'=>'daisy', 'color'=>'white');
$flowers[] = array('type'=>'orchid', 'color'=>'pink');

foreach ($flowers as $flower) {
    echo $flower['type'];
}

This will print out whatever's in column 'type' for each flower.

Upvotes: 1

Related Questions