Jump to content

[SOLVED] Can this be done with array_slice() ?


Calver

Recommended Posts

Hello, I was reading an earlier post about creating an array from another one, but it didn't work for me.

 

I have an array $columns that looks like this:

 

array

  0 =>

    array

      'Field' => string 'id' (length=2)

      'Type' => string 'int(11) unsigned' (length=16)

      'Null' => string 'NO' (length=2)

      'Key' => string 'PRI' (length=3)

      'Default' => null

      'Extra' => string 'auto_increment' (length=14)

  1 =>

    array

      'Field' => string 'firstname' (length=9)

      'Type' => string 'varchar(32)' (length=11)

      'Null' => string 'NO' (length=2)

      'Key' => string '' (length=0)

      'Default' => null

      'Extra' => string '' (length=0)

  2 =>

    array

      'Field' => string 'lastname' (length=8)

      'Type' => string 'varchar(32)' (length=11)

      'Null' => string 'NO' (length=2)

      'Key' => string '' (length=0)

      'Default' => null

      'Extra' => string '' (length=0)

 

...etc.

 

To get an array of just the Field Names I'm doing this:

 

$column_names = array();
for($i = 0; $i < count($columns); $i++) {
    $column_names[] = $columns[$i]['Field'];
}

 

How would I do this with array_slice() ?

 

You can't. But use a foreach loop instead of a for loop. And when using a for loop, don't run count() on each iteration; run it once before the loop, and store the result in a variable.

 

Thank you, I now have this:

 

$column_names = array();
$c = count($columns);
for($i = 0; $i < $c; $i++) {
    $column_names[] = $columns[$i]['Field'];
}

 

But before I got the for loop to work, I was searching for hours for the correct syntax for a foreach loop. This just copies the whole array:

 

foreach( $columns as $key => $value){
    $column_names[] = $value;
}

 

How do I specify I only want the 'Field' value?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.