Для получения полного доступа
зарегистрируйтесь.
RSS

All snippets tagged with "array" tag



Gravatar image
blacksmoke26
  • Reputation: 13
  • Snippets: 11
  • Revisions: 0
/**
 * Split the SQL dump code and return as queries array.
 * @param string $raw SQL code to parse
 * @return array List of queries
 */
function splitSqlText ( $raw ) {
	// the regex needs a trailing semicolon
	$raw = trim ( (string) $raw );

	if ( substr ( $raw, -1 ) !== ";") {
		$raw .= ";";
	}

	// i spent 3 days figuring out this line
	preg_match_all( "/(?>[^;']|(''|(?>'([^']|\\')*[^\\\]')".
		"))+;/ixU", $raw, $matches, PREG_SET_ORDER );

	$querySplit = [];

	foreach ( $matches as $match ) {
		// get rid of the trailing semicolon
		$querySplit[] = substr( $match[0], 0, -1 );
	}

	return $querySplit;
}
Gravatar image
blacksmoke26
  • Reputation: 13
  • Snippets: 11
  • Revisions: 0
/**
 * Generate mime types list using apache svn defination
 * @link http://php.net/manual/en/function.mime-content-type.php#107798
 * @return array [key=>value] pairs of mime types (extension=>mime_type)
 */
function generateMimeTypes () {
	$list = [];
	$url = 'http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types';
    
	foreach ( @explode ( "\n", @file_get_contents ($url) ) as $x ) {
		if ( isset( $x[0] )
			&& $x[0] !== '#'
			&& preg_match_all ( '#([^\s]+)#', $x, $out )
			&& isset( $out[1] )
			&& ( $c = count ( $out[1] ) ) > 1 ) {
			for ( $i = 1; $i < $c; $i++ ) {
				$key = (string) $out[1][$i];
				$list[$key] = $out[1][0];
			}
		}
	}

	return @ksort($list, \SORT_STRING )
		? $list
		: [];
}

/************
 * EXAMPLE
 ***********/
print_r ( generateMimeTypes () );

/***********
 * OUTPUT
 **********/
 [
    '3dml' => 'text/vnd.in3d.3dml'
    '3ds' => 'image/x-3ds'
    '3g2' => 'video/3gpp2'
    '3gp' => 'video/3gpp'
    '7z' => 'application/x-7z-compressed'
    'aab' => 'application/x-authorware-bin'
    'aac' => 'audio/x-aac'
    'aam' => 'application/x-authorware-map'
    'aas' => 'application/x-authorware-seg'
    'abw' => 'application/x-abiword'
    'ac' => 'application/pkix-attr-cert'
    'acc' => 'application/vnd.americandynamics.acc'
    'ace' => 'application/x-ace-compressed'
    'acu' => 'application/vnd.acucobol'
    'acutc' => 'application/vnd.acucorp'
    'adp' => 'audio/adpcm'
    'aep' => 'application/vnd.audiograph'
    'afm' => 'application/x-font-type1'
    'afp' => 'application/vnd.ibm.modcap'
    'ahead' => 'application/vnd.ahead.space'
    'ai' => 'application/postscript'
    'aif' => 'audio/x-aiff',
    ...
]
Gravatar image
blacksmoke26
  • Reputation: 13
  • Snippets: 11
  • Revisions: 0
/**
 * Divide an array into a desired number of split lists
 * @link http://www.php.net/manual/en/function.array-chunk.php#75022
 * @param array $list The Array
 * @param int $size Partition Size
 * @return array The partitioned array
 */
function columnsPartition ( array $list, $size ) {
	$listLen = count ( $list );

	if ( !$listLen || $size < 1 ) {
		return [];
	}

	$partLen = floor ( $listLen / $size );
	$partRem = $listLen % $size;
	$partition = [];
	$mark = 0;

	for ( $px = 0; $px < $size; $px++ ) {
		$increment = ( $px < $partRem ) ? $partLen + 1 : $partLen;

		$partition[ $px ] = array_slice ( $list, $mark, $increment );
		$mark += $increment;
	}

	return $partition;
}

/************
 * EXAMPLE
 ***********/
var_dump ( columnsPartition(range('A','I'), 3) );

/***********
 * OUTPUT
 **********/
array (size=3)
  0 => 
    array (size=3)
      0 => string 'A' (length=1)
      1 => string 'B' (length=1)
      2 => string 'C' (length=1)
  1 => 
    array (size=3)
      0 => string 'D' (length=1)
      1 => string 'E' (length=1)
      2 => string 'F' (length=1)
  2 => 
    array (size=3)
      0 => string 'G' (length=1)
      1 => string 'H' (length=1)
      2 => string 'I' (length=1)
dignityinside
  • Reputation: 26
  • Snippets: 21
  • Revisions: 1

Function to sort an array according to its keys which are floats casted as strings.

function sort_string_float($a, $b) {

	$a = (float) $a;
	$b = (float) $b;

	if ($a == $b) {
		return 0;
	}

	return $a < $b ? -1 : 1;

}

// use
uksort($l1_data, 'self::sort_string_float');
dignityinside
  • Reputation: 26
  • Snippets: 21
  • Revisions: 1

Check whether value an array is not empty.

$arr = ['', 'apple', ''];

if (!empty(array_filter($arr))) {
    // do something
}
dignityinside
  • Reputation: 26
  • Snippets: 21
  • Revisions: 1

Check whether value an array is not empty.

$arr = ['', 'apple', ''];

if (implode('', array_unique($arr)) != '') {
    // do something
}
samdark
  • Reputation: 348
  • Snippets: 57
  • Revisions: 5

It's possible to shuffle array once a week without storing anything. I've found the solution at StackOverflow.

It's based on initializing random number generator which is used by shuffle() with a seed that's constant for each week. date('W') is a week number in a year which fits the purpose well. After shuffling is done RNG is put back to normal by calling srand() with no argument i.e. initilizing it with random seed.

srand(date('W'));
shuffle($array);
srand();
samdark
  • Reputation: 348
  • Snippets: 57
  • Revisions: 5

Despite it's quite common requirement to assert that elements in two arrays are the same while order doesn't matter, it's not that obvious on how to do it in PHPUnit.

$array = ['b', 'a'];
$this->assertEquals(['a', 'b'], $array, '', 0.0, 10, true);
samdark
  • Reputation: 348
  • Snippets: 57
  • Revisions: 5

There are cases when you need to make sure keys specified are in the beginning of an array in the exact order they are specified.

$data = [
    'orange' => 'orange',
    'apple' => 'tasty',
    'carpet' => 'old',
    'car' => 'fast',
];

$result = orderByKeys($data, ['car', 'carpet']);

Would result in:

$data = [
    'car' => 'fast',
    'carpet' => 'old',
    'orange' => 'orange',
    'apple' => 'tasty',    
];
function orderByKeys(array $array, array $keys)
{
    foreach ($keys as $k => $v) {
        if (!array_key_exists($v, $array)) {
            unset($keys[$k]);
        }
    }

   return array_replace(array_flip($keys), $array);
}