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

 

Link to comment
Share on other sites

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?

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.