Manipulating PHP arrays with SQL

With toolkits like LINQ for .NET and the subsequant PHPLinq (thanks Nick), we're always looking for more power to manipulate data in-memory rather than writing one-off algorithms to do whatever commonly used sorting, ordering & manipulation you need.

Trent Richardson created a very small and simple JsonSQL library for JavaScript which allows you to run an extremely limited subset of SQL against a Json array/object.

I quickly ported it over to PHP 5 and it works like a charm, although the syntax for the WHERE clause isn't exactly the same but the rest ported across properly.

Be warned, this is in no way performance concious as eval() gets called in a loop to do the filtering based on your where conditions.

Download PhpSQL source code

Using PhpSQL

$testdata = array(
	array('username' => 'hello123', 'id' => 1),
	
	array('username' => 'harry', 'id' => 5),
	array('username' => 'test', 'id' => 6),
	array('username' => 'blah', 'id' => 7),
	array('username' => 'whatever', 'id' => 8),
	
	array('username' => 'hello123', 'id' => 20),
);


// Return all entries in reverse order: 20, 8, 7, 6
print_r( PhpSql::query( 'SELECT * FROM data WHERE ($id > 5) ORDER BY id DESC LIMIT 5', $testdata ) );

// Return only array('blah')
print_r( PhpSql::query( 'SELECT username FROM data WHERE ( $id == 7 )', $testdata) );

The 'FROM' clause has no effect and isn't interpreted at the moment, however in future something interesting could probably be done with it.

Source Code

/*
 * JsonSQL
 * By: Trent Richardson [http://trentrichardson.com]
 * Version 0.1
 * Last Modified: 1/1/2008
 * 
 * Copyright 2008 Trent Richardson
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * PHP port of JsonSQL
 * 
 * @author Harry Roberts
 */
class PhpSql
{
	protected $fields;
	protected $from;
	protected $where = 'true';
	protected $orderby = array();
	protected $order = 'asc';
	protected $limit = array();
	protected $result = array();
	public $data = array();
	
	public static function query( $sql, array $data )
	{
		$sql = new self( $sql, $data );
		return $sql->result;
	}
	
	public function __construct( $sql, array $data )
	{
		assert( ! empty($sql) );
		
		$rs = preg_match('/^(select)\s+([a-z0-9_\,\.\s\*]+)\s+from\s+([a-z0-9_\.]+)(?: where\s+\((.+)\))?\s*(?:order\sby\s+([a-z0-9_\,]+))?\s*(asc|desc|ascnum|descnum)?\s*(?:limit\s+([0-9_\,]+))?/i', $sql, $returnfields);
		if( $rs == FALSE )
		{
			throw new Exception( "Unable to match SQL statement" );
		}
		
	 	$this->fields = explode(',',str_replace(' ','',$returnfields[2]));
		$this->from = str_replace(' ', '', $returnfields[3]);		
		$this->where = ( ! isset($returnfields[4]) ) ? "true" : $returnfields[4];
		$this->orderby = ( ! isset($returnfields[5]) ) ? array() : explode(',',str_replace(' ', '', $returnfields[5]));
		$this->order = ( ! isset($returnfields[6]) ) ? 'asc' : $returnfields[6];
		$this->limit = ( ! isset($returnfields[7]) ) ? array() : explode(',',str_replace(' ', '', $returnfields[7]));
		
		$this->result = array();
		$this->data = $data; 
		
		$this->returnFilter( );
		$this->returnOrderBy( );
		$this->returnLimit( );
	}
	
	protected function returnFilter( )
	{
		if( empty($this->where) )
		{
			$this->where = 'true';
		}
				
		foreach( $this->data AS $__ROWKEY => $__ROWDATA )
		{
			extract( $__ROWDATA, EXTR_OVERWRITE );
			
			// Ewww - horible port directly from JavaScript!
			eval( '$__ROWSTATUS = (' . $this->where . ');' );
			if( $__ROWSTATUS )
			{
				$this->result[] = $this->returnFields($__ROWDATA);
			}
		}
	}
	
	protected function returnFields( array $scope )
	{
		if( ! count($this->fields) OR $this->fields[0] == '*' )
		{
			return $scope;
		}
		
		$returnobj = array();
		
		foreach( $this->fields AS $field_name )
		{
			$returnobj[$field_name] = $scope[$field_name];
		}
		
		return $returnobj;
	}
	
	protected function sortCallback( $a, $b )
	{
		switch( strtolower($this->order) )
		{
		case 'desc':
			return $a[$this->orderby[0]] < $b[$this->orderby[0]] ? 1 : -1;
			
		case 'descnum':
			return $a[$this->orderby[0]] - $b[$this->orderby[0]];
			
		case 'ascnum':
			return $b[$this->orderby[0]] - $a[$this->orderby[0]];
				
		case 'asc':
		default:
			return $a[$this->orderby[0]] > $b[$this->orderby[0]] ? 1 : -1;
		}
	}
	
	protected function returnOrderBy( )
	{
		usort( $this->result, array(&$this,'sortCallback') );
	}
	
	protected function returnLimit( )
	{
		switch( count($this->limit) )
		{
		case 1:
			$this->result = array_slice($this->result, 0, $this->limit[0], TRUE); 
			break;
			
		case 2:
			$this->result = array_slice($this->result, $this->limit[0] - 1, $this->limit[1], TRUE); 
			break;
		}
	}
}

2 Responses to Manipulating PHP arrays with SQL

  1. 101 Harry Roberts’ Blog: Manipulating PHP arrays with SQL | Development Blog With Code Updates : Developercast.com 2008-05-22 15:54:13

    Harry Roberts has a quick post to his blog today showing a method he’s come up with to handle PHP arrays from inside of SQL ...

  2. 102 Nick 2008-05-22 19:10:31

    Very cool, there is also PHPLinq which works similar to the .net version: http://codeplex.com/PHPLinq

Leave a Reply



About

Harry is a professional developer and sysadmin from London, UK.

He's an atheist, employed at PixelMags LLC, a socialist and has a pragmatic outlook on life, love and religion.

Bookmarks

I'm constantly finding interesting stuff, here are some of the things I've bookmarked recently:

HarryR on Faves.com