Wednesday 29 August 2012

Reduce PHP array or arrays with keys to just their values

Note: If you are using PHP5.5+ then ignore the rest of this post. You should use array_column() instead.

When you are running a query to get data from a database table like this using a framework like CodeIgniter with code like this:

$result = $this->db->select('id')->from('table')->order_by('field_n')->get()->result_array();

The $result tends to look something like this:

$result = array(
    array('id' => 1),
    array('id' => 2),
    array('id' => 3),
    ...
);

What I would like is an array of values like this:

$result = array(1, 2, 3);

I've found a good way to achieve this is to run this code (PHP5.3+):

$result = array_map(function($v){return array_shift($v);}, $result);

Doing a print_r of $result shows the code produces the flat array we want:

Array(
    [0] => 1,
    [1] => 2,
    [2] => 3,
    ...
);

There is also an added benefit in that we can select which field we want to return if there is more than one column in the table. Consider the following query:

$result = $this->db->select('id','name')->from('table')->order_by('name')->get()->result_array();

which puts these values into results:

$result = array(
    array('id' => 3, 'name' => 'Aaron'),
    array('id' => 1, 'name' => 'Brian'),
    array('id' => 2, 'name' => 'Steve'),
    ...
);

What if we just want to get the names from the array? Here's the code and the output:

$result = array_map(function($v){return $v['name'];}, $result);

Array(
    [0] => 'Aaron',
    [1] => 'Brian',
    [2] => 'Steve',
    ...
);

Monday 13 August 2012

MySQL Constraints and Foreign Keys

This is primarily for my reference alone. I continually find myself using these three SQL commands when working with constraints and foreign keys.

-- Add a foreign key constraint. I can also SET NULL, NO ACTION or RESTRICT instead of cascade
ALTER TABLE sop_version_ancestry ADD CONSTRAINT fk_sop_version_ancestry_sop
FOREIGN KEY (sop_id) REFERENCES sop(sop_id)
ON DELETE CASCADE ON UPDATE CASCADE

-- Show what constraints exist in the table (because phpmyadmin doesn't show ought)
SHOW CREATE TABLE sop_version_ancestry

-- Delete a constraint once I know what it's called from the command above
ALTER TABLE sop_version_ancestry DROP FOREIGN KEY fk_sop_version_ancestry_sop