|
użytkowników online: 91
|
OPINIE UŻYTKOWNIKÓW
|
Uważam, że serwis jest najlepszy na świecie. Wykonany rzetelnie, a wszystkie skrypty sa dopracowane. Zamieszczony materiał godny mistrza. Jestem programistą od wielu lat i bez tego serwisu nie istnieje. Upraszacza życie każdemu programiście. Imponujący jest fakt, że do twórcy serwisu zawsze można się zwrócić z prośbą o pomoc i uzyskuje się ją w bardzo krótkim czasie. Najważniejsze w tym wszystkim jest to, że można korzystać z witryny za symboliczną opłatą.
Marcin Kowalski Multinet Polska
|
|
PODRĘCZNIK PHP 5.x, 4.x, 3.x - częściowo spolszczony / źródło: www.php.net
[Spis]
[A]
[B]
[C]
[D]
[E]
[F]
[G]
[H]
[I]
[J]
[K]
[L]
[M]
[N]
[O]
[P]
[Q]
[R]
[S]
[T]
[U]
[V]
[X]
[W]
[Z]
III. Tablice
Funkcje te pozwalają na operowanie i manipulowanie tablicami na wiele
różnych sposobów. Tablice są kluczowym elementem przechowywania,
zarządzania i operowania na zbiorach zmiennych.
Obsługiwane są proste i wielowymiarowane tablice, które mogą być stworzone
przez użytkownika lub przez funkcję. Istnieją specjalne funkcje obsługi
baz danych odpowiedzialne za wypełnianie tablic danymi z zapytań do baz
danych, a także kilka innych funkcji zwracających tablice.
Zobacz rozdział podręcznika Tablice
aby uzyskać dokładne wyjaśnienie jak tablice zostały
zaimplementowane i jak się ich używa w PHP. Inne metody przetwarzania
tablic zostały opisane w rozdziale operatory tablicowe.
Do zbudowania tego rozszerzenia nie są wymagane
żadne zewnętrzne biblioteki. By używać tych funkcji, nie trzeba niczego instalować.
Są one częścią jądra PHP. To rozszerzenie nie definiuje posiada żadnych
dyrektyw konfiguracyjnych w pliku php.ini. To rozszerzenie nie posiada żadnych rodzajów zasobów.
Poniższe stałe są częścią jądra PHP a więc są zawsze widoczne.
Flagi kolejności sortowania:
Flagi typu sortowania - używane przez różne funkcje sortujące
- SORT_REGULAR
(integer)
SORT_REGULAR używana jest do porównywania
elementów w normalny sposób.
- SORT_NUMERIC
(integer)
SORT_NUMERIC używana jest do porównywania
elementów liczbowo.
- SORT_STRING
(integer)
SORT_STRING używana jest do porównywania elementów
jako ciągi tekstowe.
- SORT_LOCALE_STRING
(integer)
SORT_LOCALE_STRING używana jest do porównywania elementów
jako ciągi tekstowe w oparciu o bieżące ustawienia locale. Dodane w PHP
5.0.2.
- Spis treści
- array_change_key_case --
Zwraca tablicę ze wszystkimi kluczami tekstowymi zamienionymi na
wyłącznie małe lub wyłącznie duże litery
- array_chunk -- Podziel tablicę na kawałki
- array_combine --
Tworzy tablicę używając wartości jednej tablicy jako kluczy a drugiej
jako wartości
- array_count_values -- Zlicza wszystkie wartości w tablicy
- array_diff_assoc --
Oblicza różnicę między tablicami z dodatkowym sprawdzaniem kluczy
- array_diff_key -- Oblicza różnicę tablic używając kluczy do porównań
- array_diff_uassoc --
Computes the difference of arrays with additional index check
which is performed by a user supplied callback function
- array_diff_ukey --
Oblicza różnicę tablic używając funkcji zwrotnej do porównywania kluczy
- array_diff -- Zwraca różnice pomiędzy tablicami
- array_fill -- Wypełnij tablicę podanymi wartościami
- array_filter --
Filtruje elementy przy użyciu funkcji zwrotnej
- array_flip -- Wymienia wszystkie klucze z przypisanymi do nich wartościami w
tablicy
- array_intersect_assoc -- Computes the intersection of arrays with additional index check
- array_intersect_key -- Computes the intersection of arrays using keys for comparison
- array_intersect_uassoc -- Computes the intersection of arrays with additional index check, compares indexes by a callback function
- array_intersect_ukey -- Computes the intersection of arrays using a callback function on the keys for comparison
- array_intersect -- Zwraca przecięcie tablic
- array_key_exists --
Sprawdza czy podany klucz lub indeks istnieje w tablicy
- array_keys -- Zwraca wszystkie klucze z tablicy
- array_map --
Wykonuje funkcję zwrotną na elementach podanej tablicy
- array_merge_recursive -- Łączy dwie lub więcej tablic rekurencyjnie
- array_merge -- Łączy jedną lub więcej tablic
- array_multisort -- Sortuje wiele tablic lub wielowymiarowe tablice
- array_pad --
Dopełnij tablicę do podanej długości podanymi wartościami
- array_pop -- Zdejmij element z końca tablicy
- array_push --
Wstaw jeden lub więcej elementów na koniec tablicy
- array_rand --
Wybierz jeden lub więcej losowych elementów z tablicy
- array_reduce --
Iteracyjnie zredukuj tablicę do pojedyńczej wartości używając funkcji
zwrotnej
- array_reverse --
Zwraca tablicę z elementami ustawionymi w porządku odwrotnym
- array_search --
Przeszukuje tablicę pod kątem podanej wartości i w przypadku sukcesu
zwraca odpowiedni klucz
- array_shift --
Usuń element z początku tablicy
- array_slice -- Wytnij kawałek tablicy
- array_splice --
Usuń część tablicy i zamień ją na coś innego
- array_sum --
Oblicza sumę wartości w tablicy
- array_udiff_assoc -- Computes the difference of arrays with additional index check, compares data by a callback function
- array_udiff_uassoc -- Computes the difference of arrays with additional index check, compares data and indexes by a callback function
- array_udiff -- Computes the difference of arrays by using a callback function for data comparison
- array_uintersect_assoc -- Oblicza przecięcie tablic z dodatkowym sprawdzaniem indeksów, porównując dane przez funkcję zwrotną
- array_uintersect_uassoc -- Computes the intersection of arrays with additional index check, compares data and indexes by a callback functions
- array_uintersect -- Computes the intersection of arrays, compares data by a callback function
- array_unique -- Usuwa duplikaty wartości z tablicy
- array_unshift --
Wstaw jeden lub więcej elementów na początek tablicy
- array_values -- Zwraca wszystkie wartości z tablicy
- array_walk_recursive --
Apply a user function recursively to every member of an array
- array_walk --
Zastosuj funkcję użytkownika do każdego elementu tablicy
- array --
Stwórz tablicę
- arsort --
Sortuje tablicę w porządku odwrotnym z zachowaniem skojarzenia kluczy
- asort -- Posortuj tablicę zachowując skojarzenia kluczy
- compact --
Stwórz tablicę zawierającą zmienne i ich wartości
- count -- Zlicza ilość elementów w tablicy
- current -- Zwraca bieżący element tablicy
- each --
Zwraca bieżącą parę klucza i wartości z tablicy i przesuwa kursor tablicy
- end --
Ustawia wewnętrzny wskaźnik tablicy na ostatnim elemencie
- extract --
Importuj zmienne do bieżącej tablicy symboli z tablicy
- in_array -- Sprawdza czy wartość istnieje w tablicy
- key -- Pobiera klucz z tablicy asocjacyjnej
- krsort -- Sortuj tablicę według kluczy w porządku odwrotnym
- ksort -- Sortuj tablicę według klucza
- list --
Przypisz zmienne tak jakby były tablicą
- natcasesort --
Sortuj tablicę używając algorytmu "porządek naturalny" ignorującego
wielkość znaków
- natsort --
Sortuj tablicę używając algortmu "porządek naturalny"
- next --
Przesuń do przodu wewnętrzny wskaźnik tablicy
- pos -- Alias funkcji current()
- prev -- Cofnij wewnętrzny wskaźnik tablicy
- range --
Stwórz tablicę zawierającą przedział elementów
- reset --
Ustaw wewnętrzny wskaźnik tablicy na jej pierwszy element
- rsort -- Sortuj tablicę w porządku odwrotnym
- shuffle -- Przetasuj tablicę
- sizeof -- Alias funkcji count()
- sort -- Sortuje tablicę
- uasort --
Sortuj tablicę korzystając ze zdefiniowanej przez użytkownika funkcji
porównującej i zachowując skojarzenia kluczy
- uksort --
Sortuj tablicę według kluczy korzystając ze zdefiniowanej przez
użytkownika funkcji porównującej
- usort --
Sortuje tablicę według wartości korzystając ze zdefiniowanej przez
użytkownika funkcji porównującej
User Contributed NotesSebastian
31-Jan-2006 11:58
xxellisxx at gmail dot com:
see implode(), it does exactly what you want, but quicker.
$array = array();
$string = implode( '', $array );
xxellisxx at gmail dot com
19-Jan-2006 06:03
Super simple way of converting an array to a string.
function array_to_string($array)
{
foreach ($array as $index => $val)
{
$val2 .=$val;
}
return $val2;
}
spam at madhermit dot net
10-Jan-2006 02:26
Here is a function that recursively flattens an multidimensional array while maintaining keys. Hopefully it is useful to someone..
Example Input:
Array
(
[name] => John Doe
[email] => johndoe@earthlink.net
[addresses] => Array
(
[1] => Array
(
[address] => 555 Somewhere
[city] => Podunk
[state] => CA
[zip] => 90120
)
[2] => Array
(
[address] => 333 Someother Place
[city] => Podunk
[state] => CA
[zip] => 91103
)
)
)
Example output:
Array
(
[name] => John Doe
[email] => johndoe@earthlink.net
[address1] => 555 Somewhere
[city1] => Podunk
[state1] => CA
[zip1] => 90120
[address2] => 333 Someother Place
[city2] => Podunk
[state2] => CA
[zip2] => 91103
)
<?
function flattenArray($array,$keyname='')
{
$tmp = array();
foreach($array as $key => $value)
{
if(is_array($value))
$tmp = array_merge($tmp,flattenArray($value,$key));
else
$tmp[$key.$keyname] = $value;
}
return $tmp;
}
?>
Atomo64
04-Jan-2006 02:14
Here's a simple way to convert an array to a string and vice-versa.
Note that it does NOT support string keys,
for more information take a look at what it does:
<?php
class OptionAsArray
{
function make_the_arr($value)
{
$newValue=array();
$vals=explode('&',$value);
foreach($vals as $v)
{
if($v{0}=='@')
$newValue[]=$this->make_the_arr(
urldecode(substr($v,1)));
else
$newValue[]=urldecode($v);
}
if(empty($newValue))
return false;
else
return $newValue;
}
function make_the_value($arr)
{
$newValue=array();
foreach($arr as $value)
{
if(is_array($value))
$newValue[]='@'.urlencode(
implode('&',$this->make_the_value($value)));
else
$newValue[]=urlencode($value);
}
if(empty($newValue))
return false;
else
return $newValue;
}
}
?>
ryan1_00 at hotmail dot com
01-Jan-2006 05:02
The following will take a query result and create a dynamic table for it. Using the Key() function to get the table headers and the current() function for the actual values.
$result = mysql_query($qry) or die ("<center> ERROR: ".mysql_error()."</center>");
$x = 0;
echo "<table border=\"1\" align=\"center\">";
while($row = mysql_fetch_assoc($result))
{
if ($x == 0) // so that table headers are only created on the first pass
{
$col = (count($row)); // counts number of elements in the array
$x=1;
echo "<tr>";
for ($y=0; $y<$col; $y++)
{
echo "<th>";
echo key($row); // gets the names of the fields
echo "</th>";
next($row);
}
echo "</tr>";
}
reset($row);
echo "<tr>";
for ($y=0; $y<$col; $y++)
{
echo "<td valign=\"top\" align=\"left\">";
echo current($row);
echo"</td>";
next($row);
}
echo "</tr>";
} // end of while loop
jonathan at sharpmedia dot net
05-Dec-2005 03:37
/**
* Flattens a multimentional array.
*
* Takes a multi-dimentional array as input and returns a flattened
* array as output. Implemented using a non-recursive algorithm.
* Example:
* <code>
* $in = array('John', 'Jim', array('Jane', 'Jasmine'), 'Jake');
* $out = array_flatten($in);
* // $out = array('John', 'Jim', 'Jane', 'Jasmine', 'Jake');
* </code>
*
* @author Jonathan Sharp <jonathan@sharpmedia.net>
* @var array
* @returns array
*/
function array_flatten($array)
{
while (($v = array_shift($array)) !== null) {
if (is_array($v)) {
$array = array_merge($v, $array);
} else {
$tmp[] = $v;
}
}
return $tmp;
}
madness AT l33t DOT it
24-Nov-2005 06:18
A little function I like to use instead of the classic one, it lets me choose a better format an is overall more versatile:
<?
function get_image_size($filename, &$imageinfo){
$rawdata=getimagesize($filename, $imageinfo);
$refineddata=$rawdata;
if ($rawdata){
$refineddata=$rawdata;
$refineddata['width']=$rawdata[0];
$refineddata['height']=$rawdata[1];
$refineddata['type']=$rawdata[2];
$refineddata['attribute']=" ".$rawdata[3];
$refineddata[4]=$rawdata['mime'];
}
return $refineddata;
}
?>
Notice I also added the extra space in the attribute field, becuase I usually use it like this:
<?
echo "<img src=\\"foo.jpg"".$imgdata[attribute]." alt=\\"foo" />";
?>
This way if the attribute happens to be a null or empty value the tag doesn't contain double spaces.
stalker at ruun dot de
20-Nov-2005 10:15
I had some problems while selecting sub-arrays from multi-dimensional arrays (like the SQL-WHERE clause), so i wrote the following function:
<?php
function selectMultiArray($__multiarray,$__key,$__value) {
foreach($__multiarray as $multipart) {
if($multipart[$__key] == $__value) {
$__return[] = $multipart;
}
}
if(empty($__return)) {
return FALSE;
}
return $__return;
}
?>
hope someones finding this helpful. If you have better was for getting to this, please answer.
greets,
St4Lk3R
Rajaratnam Thavakumar--thava16 at gmail dot com
25-Oct-2005 05:16
<?php
function mydates_array($weekid,$Dateid,$no_returns){
if($weekid<=6){
$todayweek = date("D");
$myarr=array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
for($k=0;$k<=6;$k++){
if ($todayweek==$myarr[$k]){
if($k==0){
$currentdate=0;
}else{
$currentdate=$k;
}
}
}
if($Dateid==0){
$Newmyday=date("d")-$currentdate;
}else if ($Dateid==1){
$Newmyday=date("d")-($currentdate-1);
}else if ($Dateid==2){
$Newmyday=date("d")-($currentdate-2);
}else if ($Dateid==3){
$Newmyday=date("d")-($currentdate-3);
}else if ($Dateid==4){
$Newmyday=date("d")-($currentdate-4);
}else if ($Dateid==5){
$Newmyday=date("d")-($currentdate-5);
}else if ($Dateid==6){
$Newmyday=date("d")-($currentdate-6);
}
$thisweekId=$weekid;
$count=0;
$column=0;
$myval=$no_returns*5;
for($i=1; $i<=$myval; $i++){
$week1a = mktime(0, 0, 0, date("m"), $Newmyday, date("Y"));
$week123=strftime("%Y-%m-%d", $week1a);
$Newmyday=$Newmyday+7;
list ($iyear, $imonth, $idate) = split ('[-.-]', $week123);
if( $idate<10){
$idate=trim(str_replace('0','',$idate));
}
$myweekno=ceil(($idate + date("w",mktime(0,0,0,$imonth,0,$iyear)))/7);
$row=$myweekno-1;
$Mymonth[$i]=$imonth;
if ($i>1){
if ($Mymonth[$i-1]!=$Mymonth[$i]){
$column=$column+1;
}
}
$EveDates[$row][$column]=$week123;
}
$count=0;
for ( $column = 0; $column < $no_returns; $column++ ){ $mynewcount=0;
for($row = 0; $row < 6; $row++){ if($EveDates[$row][$column]!="" && $thisweekId!=6){
list ($iyear1, $imonth1, $idate1) = split ('[-.-]', $EveDates[$row][$column]);
$myweekno=ceil(($idate1 + date("w",mktime(0,0,0,$imonth1,0,$iyear1)))/7);
if($myweekno==$thisweekId+1){
$week_n1= mktime(0, 0, 0, date("m"), date("d"), date("Y"));
$week_m1=strftime("%Y-%m-%d", $week_n1);
if($count < $no_returns && $EveDates[$row][$column] >= $week_m1){
$mydates_array[$count]=$EveDates[$row][$column];
}
$count=$count+1;
}
}
else{
$mycount=0;
if ($row==5 && $thisweekId==6){
for($e=5; $e>=0; $e--){
if($EveDates[$e][$column]!=""){
break;
}
}
$week_n1= mktime(0, 0, 0, date("m"), date("d"), date("Y"));
$week_m1=strftime("%Y-%m-%d", $week_n1);
if($mycount<$no_returns && $EveDates[$e][$column] >= $week_m1){
$mydates_array[$count]=$EveDates[$e][$column];
}
$mycount=$mycount+1;
$count=$count+1;
}
}
} } return $mydates_array;
}else{
echo('WeekID Cant be more than six!');
}}
?>
<select name="eventDate" style="border:1 solid #000066" >
<? $myarray=mydates_array(6,5,10);
for ($i=0;$i<count($myarray);$i++){
list ($iyear, $imonth, $idate) = split ('[-.-]', $myarray[$i]);
$week1a = mktime(0, 0, 0,$imonth, $idate, $iyear);
$week= strftime("%A %d %B %Y", $week1a);
?>
<option value="<?=$myarray[$i]?>"><?=$week?></option>
<? }?>
</select>
msajko at gmail dot com
19-Oct-2005 10:25
array_to_string and sister function string_to_array with multi dimensional array support.
// Converts an array to a string that is safe to pass via a URL
function array_to_string($array) {
$retval = '';
$null_value = "^^^";
foreach ($array as $index => $val) {
if(gettype($val)=='array') $value='^^array^'.array_to_string($val); else $value=$val;
if (!$value)
$value = $null_value;
$retval .= urlencode(base64_encode($index)) . '|' . urlencode(base64_encode($value)) . '||';
}
return urlencode(substr($retval, 0, -2));
}
// Converts a string created by array_to_string() back into an array.
function string_to_array($string) {
$retval = array();
$string = urldecode($string);
$tmp_array = explode('||', $string);
$null_value = urlencode(base64_encode("^^^"));
foreach ($tmp_array as $tmp_val) {
list($index, $value) = explode('|', $tmp_val);
$decoded_index = base64_decode(urldecode($index));
if($value != $null_value){
$val= base64_decode(urldecode($value));
if(substr($val,0,8)=='^^array^') $val=string_to_array(substr($val,8));
$retval[$decoded_index]=$val;
}
else
$retval[$decoded_index] = NULL;
}
return $retval;
}
phpnet_spam at erif dot org
18-Oct-2005 03:36
Thought this might save someone a few hours. :) Feedback welcome, of course! Public domain, yadda yadda.
function assocSort(&$array,$key) {
if (!is_array($array) || count($array) == 0) return true;
$assocSortCompare = '$a = $a["'.$key.'"]; $b = $b["'.$key.'"];';
if (is_numeric($array[0][$key])) {
$assocSortCompare.= ' return ($a == $b) ? 0 : (($a < $b) ? -1 : 1);';
} else {
$assocSortCompare.= ' return strcmp($a,$b);';
}
$assocSortCompare = create_function('$a,$b',$assocSortCompare);
return usort($array,$assocSortCompare);
}
designatevoid at gmail dot com
14-Oct-2005 03:40
Here's an improvement to the array_to_string and string_to_array functions posted by daenders AT yahoo DOT com above.
They now handle NULL values correctly.
<?php
function array_to_string($array) {
$retval = '';
$null_value = "^^^";
foreach ($array as $index => $value) {
if (!$value)
$value = $null_value;
$retval .= urlencode(base64_encode($index)) . '|' . urlencode(base64_encode($value)) . '||';
}
return urlencode(substr($retval, 0, -2));
}
function string_to_array($string) {
$retval = array();
$string = urldecode($string);
$tmp_array = explode('||', $string);
$null_value = urlencode(base64_encode("^^^"));
foreach ($tmp_array as $tmp_val) {
list($index, $value) = explode('|', $tmp_val);
$decoded_index = base64_decode(urldecode($index));
if($value != $null_value)
$retval[$decoded_index] = base64_decode(urldecode($value));
else
$retval[$decoded_index] = NULL;
}
return $retval;
}
?>
aidan at php dot net
09-Oct-2005 10:32
za at lombardiacom dot it
27-Sep-2005 05:01
<?php
function array_swap(&$array,$key1,$key2) {
$v1=$array[$key1];
$v2=$array[$key2];
$out=array();
foreach($array as $i=>$v) {
if($i==$key1) {
$i=$key2;
$v=$v2;
} else if($i==$key2) {
$i=$key1;
$v=$v1;
}
$out[$i]=$v;
}
return $out;
}
function array_move(&$array,$key,$position) {
$from=array_search($key,array_keys($array));
$to=$from+$position;
$tot=count($array);
if($position>0) $to++;
if($to<0) $to=0;
else if($to>=$tot) $to=$tot-1;
$n=0;
$out=array();
foreach($array as $i=>$v) {
if($n==$to) $out[$key]=$array[$key];
if($n++==$from) continue;
$out[$i]=$v;
}
return $out;
}
?>
Domenic Denicola
15-Aug-2005 08:49
Another JavaScript conversion, this time to objects instead of arrays. They can be accessed the same way, but are declared much shorter, so it saves some download time for your users:
<?
function PhpArrayToJsObject($array, $objName)
{
return 'var ' . $objName . ' = ' . PhpArrayToJsObject_Recurse($array) . ";\n";
}
function PhpArrayToJsObject_Recurse($array)
{
if(! is_array($array) )
{
if ($array === null)
{
return 'null';
}
return '"' . $array . '"';
}
$retVal = "{";
$first = true;
foreach($array as $key => $value)
{
if (! $first )
{
$retVal .= ', ';
}
$first = false;
if (is_string($key) )
{
$key = '"' . $key . '"';
}
$retVal .= $key . ' : ' . PhpArrayToJsObject_Recurse($value);
}
return $retVal . "}";
}
?>
Difference from previous function: null values are no longer "" in the object, they are JavaScript null.
So for example:
<?
$theArray = array("A" => array("a", "b", "c" => array("x")), "B" => "y");
echo PhpArrayToJsObject($theArray, "myArray");
?>
Gives:
var myArray = {"A" : {0 : "a", 1 : "b", "c" : {0 : "x"}}, "B" : "y"};
You can still access them just like arrays, with myArray["A"][0] or myArray["A"]["c"][0] or whatever. Just shrinks your pages.
dieter peeters
11-Aug-2005 01:35
in response to: Domenic Denicola
I reworked your function a bit and thought i just as well could post it.
Below is the cleaner version, just cut and paste ;) The third parameter is of little use to the coder, unless javascript declaration of variables changes at some point in the future - who knows.
Only minor point is the added parameter which probably gets copied every recursive call with an empty value, though i don't know the exact ways how php handles recursion internally. Most of the time php is pretty smart when optimizing code and an empty string shouldn't take much memory anyway :)
<?php
function phpArrayToJsArray($name,$array,$prePend='var ')
{
if (is_array($array)) { $result = $name.' = new Array();'."\n";
foreach ($array as $key => $value) {
$result .= phpArrayToJsArray($name.'["'.$key.'"]',$value,'');
}
} else { $result = $name.' = "'.$array.'";'."\n";
}
return $prePend.$result;
}
?>
michael at imreo com
21-Jul-2005 02:20
Reply to array_cartesian_product of skopek at mediatac dot com, 13-Oct-2004 12:44:
Your function does not work in my configuration (WinXP, apache 2.0, php 4.3.11).
This part of code:
...
} else { //if next returns false, then reset and go on with previuos array...
reset($arrays[$j]);
}
...
cause infinite loop.
Replacing to
...
} elseif (isset($arrays[$j])) {
reset($arrays[$j]);
}
...
works good.
My complete working function (additionaly strings as keys are allowed):
<?php
function array_cartesian_product($arrays)
{
$result = array();
$arrays = array_values($arrays);
$sizeIn = sizeof($arrays);
$size = $sizeIn > 0 ? 1 : 0;
foreach ($arrays as $array)
$size = $size * sizeof($array);
for ($i = 0; $i < $size; $i ++)
{
$result[$i] = array();
for ($j = 0; $j < $sizeIn; $j ++)
array_push($result[$i], current($arrays[$j]));
for ($j = ($sizeIn -1); $j >= 0; $j --)
{
if (next($arrays[$j]))
break;
elseif (isset ($arrays[$j]))
reset($arrays[$j]);
}
}
return $result;
}
?>
daenders AT yahoo DOT com
08-Jul-2005 10:49
Several people here have posted functions for converting arrays to strings, but nobody posted a sister function that would convert it back. Also, their data is not URL safe. These functions are URL safe, hide the data by MIME encoding it, and are much shorter. Enjoy. :-)
<?php
function array_to_string($array) {
$retval = '';
foreach ($array as $index => $value) {
$retval .= urlencode(base64_encode($index)) . '|' . urlencode(base64_encode($value)) . '||';
}
return urlencode(substr($retval, 0, -2));
}
function string_to_array($string) {
$retval = array();
$string = urldecode($string);
$tmp_array = explode('||', $string);
foreach ($tmp_array as $tmp_val) {
list($index, $value) = explode('|', $tmp_val);
$retval[base64_decode(urldecode($index))] = base64_decode(urldecode($value));
}
return $retval;
}
$array1 = array('index1' => 'val1', 'index2' => 'val2', 'index3' => 'val3');
echo '<pre>'; print_r($array1); echo '</pre>';
$string = array_to_string($array1);
echo '$string: '.$string.'<br />';
$array2 = string_to_array($string);
echo '<pre>'; print_r($array2); echo '</pre>';
?>
casey geene
30-Apr-2005 12:14
Handy function to walk through an array to get an offset with a given path.
<?php
function &array_path(&$array, $path) {
if(!is_array($array)) {
trigger_error('array_path(): First argument should be an array', E_USER_WARNING);
}
settype($path, 'array');
$offset =& $array;
foreach ($path as $index) {
if (!isset($offset[$index])) {
trigger_error("Undefined offset: $index");
return false;
}
$offset =& $offset[$index];
}
return $offset;
}
$a = array(
1 => array(
2 => array(
3 => 'hi'
)
)
);
echo array_path($a, array(1, 2, 3));
$ref =& array_path($a, array(1, 2));
$ref = array('hello');
?>
garis at intec dot edu dot do
29-Apr-2005 05:55
this array are always used on form querys... is a nice way to simplify the date inputs
<?php
$dia = array('', 'Lunes','Martes','Miercoles','Jueves','Viernes','Sabado', 'Domingo');
$mes = array('', 'Enero','Febrero','Marzo','Abril','Mayo','Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre');
?>
and you call monday like $dia['1']...
i used it on a form, that have a lot of date inputs, cuz i wanted to minimize the size of my file..
admin at snibworks dot com
20-Apr-2005 05:40
I have made a new array function called array_split.
It's like explode() for arrays. It searches the array for a specific value and splits the array into chunks divided by that value.
<?php
function array_split($key, $array)
{
if(!is_array($array))trigger_error("Invalid type provided for
second parameter of array_split",E_USER_ERROR);
$rarray = array();
$curkey = 0;
foreach($array as $value)
{
if($value == $key)
{
$curkey++;
continue;
}
$rarray[$curkey][] = $value;
}
return $rarray;
}
$new_array = array('one','two','break','three',
'break','four','five','six');
var_dump(array_split('break',$new_array));
?>
ktaufik(at)gmail(dot)com
16-Feb-2005 01:31
For you who works for localized "say" number to letter ( ex , 7=> seven, 8=>eight) for Bahasa Indonesia.
Indonesia "say" or "Terbilang" is based on 3 digit number.
thousands, millions and trillions .... will be based on the 3 digit number.
In Indonesia you say 137 as "Seratus Tiga Puluh Tujuh"
<?php
$x=rand(0,9);
$y=rand(0,9);
$z=rand(0,9);
function display_angka_bilangan($n) {
$angka = array(
1 => 'satu',
2 => 'dua',
3 => 'tiga',
4 => 'empat',
5 => "lima",
6 => 'enam',
7 => 'tujuh',
8 => 'delapan',
9 => 'sembilan'
);
return $angka[$n];
}
if ($x==1){$terbilangx="seratus ";}
elseif ($x==0){$terbilangx='';}
else {$terbilangx=''.display_angka_bilangan($x).' '.'ratus ';}
if ($y==0){$terbilangy='';}
elseif ($y==1 && $z==1){$terbilangy="sebelas";$terbilangz='';}
elseif ($y==1 && $z==0){$terbilangy="sepuluh ";$terbilangz='';}
elseif ($y==1 && $z!==1 && $z!==0){$terbilangy=''.display_angka_bilangan($z).' belas ';}
else {$terbilangy=''.display_angka_bilangan($y).' '.'puluh ';}
if ($z==0){$terbilangz="";}
elseif ($z==0 && $y==1){$terbilangz="";}
elseif ($z==1 && $y==1){$terbilangz="";}
elseif($y==0) {$terbilangz="".display_angka_bilangan($z);}
elseif ($y==1 && $z!==1 && $z!==0) {$terbilangz="";}
else {$terbilangz="".display_angka_bilangan($z);};
$terbilang=$terbilangx.$terbilangy.$terbilangz;
echo $x.$y.$z." ";
echo $terbilang;
?>
Hope it is useful
ktaufik(at)gmail(dot)com
tYZ
08-Feb-2005 10:53
In reply to zubfatal, root at it dot dk (25-Nov-2004 02:06):
Instead of writing all those functions you could also use:
array_avg: array_sum($arr) / sizeof($arr);
array_max: max($arr);
array_min: min($arr)
daniel _dot eherbert _at gmail _dot com
02-Feb-2005 06:52
i was unable to use normal means to shift an array element up or down, so i had to write a function to do it... i havent had the chance to test it, but the method is there...
<?
$stuff[0] = 'a';
$stuff[1] = 'b';
$stuff[2] = 'c';
$stuff[3] = 'd';
function array_shift($array,$value,$direction = 'up')
{
$temp = $array;
while ($array_value = current($array))
{
if ($array_value == $value)
{
$key = key($array);
break;
}
next($array);
}
if ( !isset($key) )
{
return false;
}
if ( $key == 0 && $direction == 'up' )
{
return $array;
}
if ( $key == (count($array)-1) && $direction == 'down' )
{
return $array;
}
switch ($direction)
{
case 'up':
$factor = -1;
break;
case 'down':
$factor = 1;
break;
}
$temp[$key+$factor] = $array[$key];
$temp[$key] = $array[$key+$factor];
return $temp;
}
?>
$stuff = array_shift($stuff,'c','up'); - will move c up and b down
$stuff = array_shift($stuff,'a','down'); - will move a down and b up
$stuff = array_shift($stuff,'a','up'); - will return the original array
$stuff = array_shift($stuff,'d','down'); - will return the original array
... if the element value could not be found it probably should return the original array instead of false...
m227(a)poczta.onet.pl
20-Jan-2005 05:18
How to count dimensions in multi-array? (corrected)
previous version didn't work when called more than one time.
($dimcount was preserved from previous call)
This is the way I corrected this:
function countdim($array)
{
if (is_array(reset($array)))
$return = countdim(reset($array)) + 1;
else
$return = 1;
return $return;
}
This function will return int number of array dimensions.
skopek at mediatac dot com
13-Oct-2004 12:44
I needed a function, that returns the cartesian product of some input-arrays in an array. Here is the function that can do that:
<?php
function array_cartesian_product($arrays) {
$cartesic = array();
$size=(sizeof($arrays)>0)?1:0;
foreach($arrays as $array)
{
$size= $size*sizeof($array);
}
for($i=0; $i<$size;$i++) {
$cartesic[$i] = array();
for($j=0;$j<sizeof($arrays);$j++)
{
$current = current($arrays[$j]);
array_push($cartesic[$i], $current);
}
for($j=(sizeof($arrays)-1);$j>=0;$j--)
{
if(next($arrays[$j])) {
break;
} else { reset($arrays[$j]);
}
}
}
return $cartesic;
}
$arrays[0] = array("a", "b");
$arrays[1] = array("x", "y", "z");
print_r(array_cartesian_product($arrays));
?>
The output is:
Array
(
[0] => Array
(
[0] => a
[1] => x
)
[1] => Array
(
[0] => a
[1] => y
)
[2] => Array
(
[0] => a
[1] => z
)
[3] => Array
(
[0] => b
[1] => x
)
[4] => Array
(
[0] => b
[1] => y
)
[5] => Array
(
[0] => b
[1] => z
)
)
Greets
Jan
davidj at boundlessgallery dot DISLIKESPAM dot com
02-Apr-2004 03:10
A recursive function for flattening nested arrays:
<?php
function flatten_array($array) {
for($x = 0; $x < sizeof($array); $x++) {
$element = $array[$x];
if(is_array($element)) {
$results = flatten_array($element);
for($y = 0; $y < sizeof($results); $y++) {
$flat_array[] = $results[$y];
}
} else {
$flat_array[] = $element;
}
}
return $flat_array;
}
?>
Example:
<?php
$array = array("0", "1", array("2", "3", array("4", array("5", "6"), "7", "8")), "9", "10", array("11"), array());
print_r($array);
print_r(flatten_array($array));
?>
Output:
Array
(
[0] => 0
[1] => 1
[2] => Array
(
[0] => 2
[1] => 3
[2] => Array
(
[0] => 4
[1] => Array
(
[0] => 5
[1] => 6
)
[2] => 7
[3] => 8
)
)
[3] => 9
[4] => 10
[5] => Array
(
[0] => 11
)
[6] => Array
(
)
)
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
)
31-Jan-2004 10:29
To remove an element from an array use unset(). Example:
unset($bar['mushroomsoup']);
28-Aug-2003 03:09
Remember that if you want to remove an element from an array, you must use "unset" - Do not set the value to null.
szymon at mazurek dot info
24-Aug-2003 02:46
How to count dimensions in multi-array?
This is the way I do this:
function countdim($array) {
static $dimcount = 1;
if (is_array(reset($array))) {
$dimcount++;
$return = countdim(reset($array));
} else {
$return = $dimcount;
}
return $return;
}
This function will return int number of array dimensions.
jeroen at php dot net
29-Aug-2001 10:58
|