Tag Archive for array

Convert Array to Object, infinite dimensions

<?php

$array = array (
array (

),
array (
array (

)
)
);

function bindArrayToObject($array) {
$return = new stdClass();
foreach ($array as $k => $v) {
if (is_array($v)) {
$return->$k = bindArrayToObject($v);
}
else {
$return->$k = $v;
}
}

return $return;
}

$newObject = bindArrayToObject($array);
print_r($newObject);
?>

source

Sort Element Array by DOM Position

var DOMPositionComparator = function(a,b){
if(Prototype.Browser.IE){
return a.sourceIndex - b.sourceIndex;
}else if(Prototype.Browser.Gecko){
return 3 - (a.compareDocumentPosition(b) & 6);
}
};

var sortedFields = $$('img.L,img.M').sort(DOMPositionComparator);

source

AS3 Collection Class

package {
/**
* Collection Class
* Version 1.0, 2008-09-20
* Created by Michael James Williams
* <a href="http://www.michaeljameswilliams.com" >http://www.michaeljameswilliams.com</a>
*/
public class Collection extends Object {

public var _collection:Array;

/**
* Creates a new collection populated with the specified values
* @param	... values
*/
public function Collection(... values) {
_collection = new Array();
addItems(values);
}

/**
* Adds the specified items to the collection
* @param	... items
*/
public function addItems(... items):void {
for each (var item in items) {
if (item is Array) {
for each (var subItem in item) {
addItems(subItem);
}
} else if (item is Collection) {
for each (subItem in item.itemList) {
addItems(subItem);
}
} else {
if (!contains(item)) {
_collection.push(item);
}
}
}
}

/**
* Removes all of the specified items from the collection
* @param	... items
*/
public function removeItems(... items):void {
for each (var item in items) {
if (item is Array) {
for each (var subItem in item) {
removeItems(subItem);
}
} else if (item is Collection) {
for each (subItem in item.itemList) {
removeItems(subItem);
}
} else if (contains(item)) {
_collection.splice(_collection.indexOf(item), 1);
}
}
}

/**
* Returns true iff collection contains (or is) specified item
* @param	item
* @return
*/
public function contains(item):Boolean {
if ((item is Array) || (item is Collection)) {
return containsAll(item);
} else {
if ((_collection.indexOf(item) > -1) || (this === item)) {
return true;
} else {
return false;
}
}
}

/**
* Returns true iff collection contains all specified items (including subitems of an array or collection)
* @param	... items
* @return
*/
public function containsAll(... items):Boolean {
var all:Boolean = true;
for each (var item in items) {
if (item is Array) {
for each (var subItem in item) {
if (!_collection.containsAll(subItem)) { all = false; }
}
} else if (item is Collection) {
for each (subItem in item.itemList) {
if (!_collection.containsAll(subItem)) { all = false; }
}
} else {
if (!_collection.contains(item)) { all = false; }
}
}
return all;
}

/**
* Returns true iff collection contains any of the specified items (including subitems of an array or collection)
* @param	... items
* @return
*/
public function containsAny(... items):Boolean {
var any:Boolean = false;
for each (var item in items) {
if (item is Array) {
for each (var subItem in item) {
if (!_collection.containsAny(subItem)) {
any = true;
break;
}
}
} else if (item is Collection) {
for each (subItem in item.itemList) {
if (!_collection.containsAny(subItem)) {
any = true;
break;
}
}
} else {
if (!_collection.contains(item)) {
any = true;
break;
}
}
}
return any;
}

/**
* Executes a test function on each item in the collection and constructs a new collection of all items that return true.
* @param	callback
* @param	thisObject
* @return
*/
public function filter(callback:Function, thisObject:* = null):Collection {
var filtered:Collection = new Collection();
filtered.addItems(_collection.filter(callback, thisObject));
return filtered;
}

/**
* Executes a function on each item in the collection.
* @param	callback
* @param	thisObject
*/
public function forEach(callback:Function, thisObject:* = null):void {
_collection.forEach(callback, thisObject);
}

/**
* Converts the elements in a collection to strings, inserts the specified separator between the elements, concatenates them, and returns the resulting string.
* @param	sep
* @return
*/
public function join(sep:*):String {
return _collection.join(sep);
}

/**
* Executes a function on each item in an collection, and constructs a new collection of items corresponding to the results of the function on each item in the original collection.
* @param	callback
* @param	thisObject
* @return
*/
public function map(callback:Function, thisObject:* = null):Collection {
var mappedArray:Array = _collection.map(callback, thisObject);
var mappedCollection:Collection = new Collection();
for each (var item in mappedArray) {
mappedCollection.addItems(item);
}
return mappedCollection;
}

/**
* Executes a test function on each item in the collection until an item is reached that returns true. Use this method to determine whether any items in a collection meet a criterion, such as having a value less than a particular number.
* @param	callback
* @param	thisObject
* @return
*/
public function some(callback:Function, thisObject:* = null):Boolean {
return _collection.some(callback, thisObject);
}

/**
* Executes a test function on each item in the collection until an item is reached that returns false for the specified function. You use this method to determine whether all items in a collection meet a criterion, such as having values less than a particular number.
* @param	callback
* @param	thisObject
* @return
*/
public function every(callback:Function, thisObject:* = null):Boolean {
return _collection.every(callback, thisObject);
}

/**
* Returns a collection made up of items in this collection for which item.property==value
* @param	property
* @param	value
* @return
*/
public function subCollection(property:String, value:*):Collection {
///Ideally this would accept a method name and a ...params and check to see if item.method(...params)==true
var subCollection:Collection = new Collection();
for each (var item in _collection) {
try {
if (item[property]==value) {
subCollection.addItems(item);
}
} catch (err) {
//this is likely to be very very error prone if the programmer isn't careful so we'll just break out of the loop
break;
}
}
return subCollection;
}

/**
* Returns a collection made up of all items that are in both this collection and the specified collection
* @param	coll
* @return
*/
public function intersection(coll:Collection):Collection {
var intersectColl:Collection=new Collection();
for each (var item in coll.itemList) {
if (this.contains(item)) {
intersectColl.addItems(item);
}
}
return intersectColl;
}

/**
* Returns the intersection of this collection with an arbitrary number of other collections
* @param	... colls
* @return
*/
public function intersectMany(... colls):Collection {
var intersectColl:Collection = new Collection();
intersectColl.addItems(_collection);
for each (var subItem in colls) {
if (subItem is Collection) {
intersectColl = intersectColl.intersection(subItem);
}
}
return intersectColl;
}

/**
* Returns a collection made up of all items that are in either this collection or the specified collection (or both)
* @param	coll
* @return
*/
public function union(coll:Collection):Collection {
var unionColl:Collection = new Collection();
unionColl.addItems(itemList, coll);
return unionColl;
}

/**
* Returns the union of this collection with an arbitrary number of other collections
* @param	... colls
* @return
*/
public function unionMany(... colls):Collection {
var unionColl:Collection = new Collection();
unionColl.addItems(_collection);
for each (var subItem in colls) {
if (subItem is Collection) {
unionColl = unionColl.union(subItem);
}
}
return unionColl;
}

/**
* Returns the relative complement of the specified collection in this collection
* A.relComp(B) := AB
* @param	coll
* @return
*/
public function relComp(coll):Collection {
///Returns the relative complement of the specified collection in this collection
///A.relComp(B) := AB
///i.e. returns a collection containing items that are in this collection but not in the specified collection
var rcColl:Collection = new Collection();
rcColl.addItems(_collection);
rcColl.removeItems(coll);
return rcColl;
}

/**
* Returns the relative complement of the union of the specified collections in this collection
* @param	... colls
* @return
*/
public function relCompMany(... colls):Collection {
var rcColl:Collection = new Collection();
rcColl.addItems(_collection);
for each (var subItem in colls) {
if (subItem is Collection) {
rcColl.removeItems(subItem);
}
}
return rcColl;
}

/**
* Returns the number of items in the collection
*/
public function get numItems():uint {
return _collection.length;
}

/**
* Exposes the underlying array; use this only for e.g. for-each loops
*/
public function get itemList():Array {
return _collection;
}
}
}

source

Element Collection Manipulation Shortcut Using MooTools 1.2

// MooTools Looping Example (Bad/Long)

$$('.toggler').each(function(el) {
el.addEvent('mouseenter',function(e) {
el.fireEvent('click');
});
});

// MooTools Collection Example (Good/Short)

$$('.toggler').addEvent('mouseenter', function() { this.fireEvent('click'); });

source

Remove an item of array

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};

source

Random Seeded Array Shuffle

function fyshuffle(&$items,$seedstring) {
if (!$seedstring) {
$seedval = time();
} else {
if (is_numeric($seedstring)) {
$seedval = $seedstring;
} else {
for($i=0;$i<=strlen($seedstring);$i++) {
$seedval += ord($seedstring[$i]);
}
}

srand($seedval);
for ($i = count($items) - 1; $i > 0; $i--) {
$j = @rand(0, $i);
$tmp = $items[$i];
$items[$i] = $items[$j];
$items[$j] = $tmp;
}
}

source

array to object, object to array

// Funcion de Objeto a Array
function object_to_array($object)
{
if(is_array($object) || is_object($object))
{
$array = array();
foreach($object as $key => $value)
{
$array[$key] = object_to_array($value);
}
return $array;
}
return $object;
}

// Funcion de Array a Objeto
function array_to_object($array = array())
{
return (object) $array;
}

source

Sort a bidimensional array

// rellenamos una array
$array[] = array('nombre'=>'miquel','edad'=>22);
$array[] = array('nombre'=>'carlos','edad'=>29);
$array[] = array('nombre'=>'hermann','edad'=>24);
$array[] = array('nombre'=>'jorge','edad'=>21);
$array[] = array('nombre'=>'daniel','edad'=>25);
// declaramos la función de ordenación
function cmp($a, $b)
{
if ($a["edad"] == $b["edad"]) {
return 0;
}
return ($a["edad"] <$b["edad"]) ? -1 : 1;
}
// ordenamos segun la función de ordenación
usort($array, "cmp");
echo '<pre>';
print_r($array);
echo '</pre>';

source

Array.prune

//removes a section of the array, returning what's left; does not affect the original array
//(essentially the opposite of Array.slice)
//example:
//	var x = ['a', 'b', 'c', 'd'];
//	var y = x.prune(1,3);
//	alert(x);	//['a', 'b', 'c', 'd']
//	alert(y);	//['a', 'd']
//end argument is optional
Array.prototype.prune = function(start, end)
{
var result = this.slice(0, start);
if(!isNaN(end)) result.concat(this.slice(end));
return result;
}

source

Loop email reading an Array

<?php

set_time_limit(0); // this will keep the script from stopping if it takes longer then 30 seconds, must have this here
$emailaddress = array('test1@test.com', 'test2@test.com', 'test3@test.com', 'test4@test.com', 'test5@test.com', 'test6@test.com');
$emailsubject = "This is a sample subject!";
$emailbody = file_get_contents("email.html");
$fromaddress = "name@domain.tld";
$i = count($emailaddress);
$z = 0;

// here we check how many  email address's we have, if its is 0, then we don't start the email function
if ($i != 0)
{// start if

// Lets loop until we reach the count from email address array
while ($i != $z)
{// start while

// here we send the email to the varables from above, using the email array incrament
mail($emailaddress[$z], $emailsubject, $emailbody, "From: " .$fromaddress. "
X-Mailer: PHP 4.x");

// lets echo out that the email was sent
echo $z + 1 . " out of " . $i . " emails sent. (" . $emailaddress[$z] . ")<br>";

// increment the array one, so we get a new email address from the array
++$z;

}// end while

}//end if

else
{//start else

// we echo out that no emails where found in the array and end the script
echo "Warning: No emails in array.";

}// end else

?>

source