PHP: Tablice - Manual
PHP  
downloads | documentation | faq | getting help | | php.net sites | links 
search for in the  
previousvirtualarray_change_key_casenext
Last updated: Tue, 16 Jul 2002
view this page in Printer friendly version | English | Brazilian Portuguese | Chinese | Czech | Dutch | Finnish | French | German | Hungarian | Italian | Japanese | Korean | Romanian | Russian | Spanish | Turkish

II. Tablice

Wprowadzenie

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.

Wymagania

Te funkcje s� cz�ci� modu�u podstawowego, dlatego s� zawsze dost�pne.

Instalacja

By u�ywa� tych funkcji, nie trzeba niczego instalowa�. S� one cz�ci� j�dra PHP.

Konfiguracja startowa

To rozszerzenie nie definiuje �adnych dyrektyw konfiguracyjnych.

Typy zasob�w

To rozszerzenie nie definiuje �adnych rodzaj�w zasob�w.

Predefiniowane sta�e

Poni�sze sta�e s� zdefiniowane w tym rozszerzeniu i staj� si� dost�pne, gdy rozszerzenie jest dokompilowane do PHP, lub za�adowane dynamicznie przy starcie.

CASE_LOWER (integer)

CASE_LOWER jest u�ywana w funkcji array_change_key_case() do konwersji kluczy tablicy do samych ma�ych liter. Jest to tak�e domy�lny przypadek dla array_change_key_case().

CASE_UPPER (integer)

CASE_UPPER jest u�ywana w funkcji array_change_key_case() do konwersji kluczy tablicy do samych du�ych liter.

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_count_values -- Zlicza wszystkie warto�ci w tablicy
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 -- Odwraca wszystkie warto�ci w tablicy
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 dwie 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_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 --  Zastosuj funkcj� u�ytkownika do ka�dego elementu tablicy
array --  Stw�rz tablic�
arsort --  Sortuj tablic� w porz�dku odwrotnym i zachowaj 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 --  Ustaw wewn�trzny wska�nik tablicy na ostatnim elemencie
extract --  Importuj zmienne do bie��cej tabeli symboli z tablicy
in_array -- Zwraca TRUE je�li 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 -- Pobierz bie��cy element z tablicy
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 -- Policz ilo�� element�w w zmiennej
sort -- Sortuj 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 --  Sortuj tablic� wed�ug warto�ci korzystaj�c ze zdefiniowanej przez u�ytkownika funkcji por�wnuj�cej
User Contributed Notes
Tablice
add a note about notes

01-Feb-1999 12:30

use the max function to get the highest value of an array e.g:
   $maxval = max($array);


04-Apr-2001 09:58

I added this note to array_pop, but it's probably more applicable here:

If you use array_pop, the numeric indices  will be renumbered if there are
any gaps. So if you start with

$a[5]="five"; 
$a[6]="six"; 

and then do array_pop($a), you now have $a[0]="five", not
$a[5]="five", as you might expect. In other words, $a does not
necessarily equal array_pop(array_push($a, 1)).

Response in the bug database was the following:

--
Presently, all splice-derived functions reorder numeric keys. There's not
much to do about it, since it's the way Zend Engine handles numeric hash
keys. Changing it either way won't bring more consistent  functionality,
so in the meantime it is just as it is.
--

I'd disagree that changing my array indices is consistent, but there you
are. I don't know which array functions are splice-derived, so look out
for this.


29-Aug-2001 07:58

You should really read 
, there is a lot of info there about how to handle arrays, how to check
wether indices are set, how to modify an array, anything.


29-Jan-2002 09:55

You should pay attention to the fact that some functions act directly on
the array (such as asort) and some don't touch the array but return a copy
(such as array_reverse).  If you use one in the improper context you won't
get a warning. It took me a while to notice this as I do a lot of coding
by memory and don't refer to the function documentation unless I need to.


05-Feb-2002 05:56

To display the value of a variable from a two dimentional array inside a
quoted string, use the following syntax:

<?php

$var = array(
    'name' => array(
        'first' => 'Caleb',
        'last' => 'Maclennan'
      )
  );

echo "My first name is {$var[name][first]}!";

?>


14-Apr-2002 09:34

Looping through an array, and printing each item:

for ($i = 0; $i < count($array_name); $i++) { echo("$i -
$arrayname[$i]"); }


20-Apr-2002 12:43

You should pay attention to the fact that some functions act directly on
the array (such as asort) and some don't touch the array but return a
copy
(such as array_reverse).

Tim Burly


13-May-2002 07:12

I bet there was someone else that needed to translate an associative array
from php into, lets say, an associative array in JavaScript (or other
programing language)
You can use these functions i wrote, which i tried to be as customizable
as possible, for use in many other languages.

For example, in JavaScript an associative array would look like:

array: {
    category1: {
        title: 'cat title 1',
        name: 'cat_name_1',
        desc: 'cat desc 1'
    },
    category2: {
        title: 'cat title 2',
        name: 'cat_name_2',
        desc: 'cat desc 2'
    },
    property: value
}

Here are the functions i wrote: (legend at the end)

function ga($arr, $sep, $grp, $elemsep, $end, $ind, $indpos) {
	$newarr = "";
	foreach( $arr as $key=>$val ) {
		
		if( is_array( $val ) ) {
		
			$newarr .= str_repeat( $ind, $indpos ).$key.$sep.$grp[0].$end;
			$newarr .= ga( $val, $sep, $grp, $elemsep, $end, $ind, $indpos + 1 );
			$newarr .= str_repeat( $ind, $indpos ).$grp[1];
		}
		else
			$newarr .= str_repeat( $ind, $indpos ).$key.$sep.$val;
	
		$newarr .= ( ( $arr[$key] == end( $arr ) ) ? "" : $elemsep ) .
$end;
	}

	return $newarr;
}

function genarr( $arrname, $genfunc, $sep = ": ", $grp = array(
"{", "}" ) , $elemsep = ",", $end =
"\n", $ind = "\t", $indpos = 1 ) {
	global $$arrname;
	return $arrname.$sep.$grp[0].$end.$genfunc ($$arrname, $sep, $grp,
$elemsep, $end, $ind, $indpos).$grp[1];
}

Legend:

$arr = the php associative array to transform

$sep = the separator char/string between the key and the value (in
JavaScript its ":", in PHP its "=>")

$grp = an array having the 1st element as the "new array"
character and the 2nd element as the "array end" character (in
javaScript they are "{" and "}", in PHP they are
"array(" and ")" )

$elemsep = elements separator (in javascript and PHP its "," )

$end = the caracter appended at the end of an element

$ind = indentation character

$indpos = default indent 

NOTE: if you would like an inline output, then set the $end = ""
and the $ind = "".
If you want a stylish output you can set the $end = "\n" and
$ind = "\t".

$genfunc = a STRING evaluating to the the fetching function name (in this
case "ga")

$arrname = a STRING, evaluating to the array variable name (note the
calling to it by "$$arrname" )

NOTE: for JavaScript, i set all arguments by default in the
"genarr" function.

EXAMPLE:

Supposing you have a PHP associative array:

$bob = array( 
    "key1" => array (
         ......

then for javaScript, you should call the "genarr" function like
this:

$JSArray = genarr( "bob", "ga" )

note the arguments: "bob" and "ga"

This will result in a Javascript array like this:

bob: {
    key1: {
       .....

Hope it helped because i need to have a huge JavaScript associative array
for one of the sites i run but also the same array in PHP and its a hell
of a job updating 2 pieces of code when PHP can generate it dynamically,
thus its sufficient to make changes only in the PHP code.

Cheers

P.S. let me know if you found it useful


13-May-2002 10:51

In the last post i missed something in the fetching function. It had
troubles handling boolean values and i forgot strings as well. Also,
detecting the end of a sub-array didnt work as expected. Here are the new
versions that worked with everything i threw at it:

function ga($arr, $sep, $grp, $elemsep, $str, $end, $ind, $indpos) {

	$newarr = "";
	$len = count( $arr );
	for( $i=0; $i<$len; $i++ ) {

		//get current key,value pair
		list( $key, $val ) = each( $arr );
		
		if( is_array( $val ) ) {
			//calling recursively if it hits a sub-array
			$newarr .= str_repeat( $ind, $indpos ).$key.$sep.$grp[0].$end;
			$newarr .= ga( $val, $sep, $grp, $elemsep, $str, $end, $ind, $indpos +
1 );
			$newarr .= str_repeat( $ind, $indpos ).$grp[1];
		}
		else {
			$newarr .= str_repeat( $ind, $indpos ).$key.$sep;
			//determine element type
			$newarr .= ( is_bool( $val ) ) ? (($val) ? 'true' : 'false') : (
is_string( $val ) ? $str.addslashes( $val ).$str : $val );
		}

		//if last element then don't add $elemsep after it
		$newarr .= ( $i == $len-1 ) ? $end : $elemsep.$end;
	}

	return $newarr;
}

	
function genarr( $arrname, $genfunc, $sep = ': ', $grp = array( '{', '}' )
, $elemsep = ',', $str = '"', $end = "\r\n", $ind =
"\t", $indpos = 1 ) {
	global $$arrname;
	return $arrname.$sep.$grp[0].$end.$genfunc ($$arrname, $sep, $grp,
$elemsep, $str, $end, $ind, $indpos).$grp[1];
}

I also added addslashes() to string values. There is a new argument:

$str = the string delimiter (usually " \" " or " \'
" ). The second function only has the new argument modified. The rest
is the same.

Please let me know if you find anything going wrong.

Cheers


28-May-2002 04:10

here's a little function i wrote to convert any multidimensional array to
an xml tree. it has this prototype:

string arr2xml (array array, [string tree_name])

if they are associative arrays, the element keys will be used as node
names. any numeric arrays will be filled in with level1, level2 .. if you
omit the second (optional) argument, it uses level0 as the top of the
tree.

function arr2xml ($arr)
{
   if (func_num_args () < 3)
   {
      $wrapper = (func_num_args < 2) ? array ($arr) : array
(func_get_arg(1)=>$arr);
      $xml = arr2xml ($wrapper, '', 0);
   }
   else
   {
      $level = func_get_arg (2);
      while (list ($key, $val) = each ($arr))
      {
         if ($key === (int)$key) $key = 'level'.$level;
         $xml .= '<'.$key.'>';
         if (gettype ($val) == 'array')
         {
            $xml .= arr2xml ($val, '', $level+1);
         }
            else
         {
            $xml .= $val;
         }
         $xml .= '</'.$key.'>';
      }
   }
   return $xml;
}


29-May-2002 02:17

could an admin please remove my last post? this is a much better rewrite of
the arr2xml () function.

its more sensibly written and flexible now. theres only one required
argument, the array itself. it has this prototype: 

string arr2xml (array array, [string tree_name], [[int level]) 

use the second argument if you want to specify a name for the top of the
tree - otherwise it defaults to level0. the first call to the function is
kind of a dummy top level that wraps the array inside another array and
calls the function for real. 

dont use the third argument. thats used to keep track of the levels in all
the recursive calls. 

heres the code: 

function arr2xml ($arr)
{
   if (func_num_args () < 3)
   {
      $wrapper = (func_num_args < 2) ? array ($arr) : array
(func_get_arg(1)=>$arr);
      $xml = arr2xml ($wrapper, '', 0);
   }
   else
   {
      $level = func_get_arg (2);
      while (list ($key, $val) = each ($arr))
      {
         if ($key === (int)$key) $key = 'level'.$level;
         $xml .= '<'.$key.'>';
         if (gettype ($val) == 'array')
         {
            $xml .= arr2xml ($val, '', $level+1);
         }
            else
         {
            $xml .= $val;
         }
         $xml .= '</'.$key.'>';
      }
   }
   return $xml;
}

bishop
07-Jun-2002 05:42

Sometimes you need an array that has all keys exactly equal to all values. 
For example, arrays that look like:
array('a' => 'a', 'b' => 'b', 'c' => 'c');

You can either do it manually (a pain for count($a) > 2), or use
array_smear():

/* smear values across into keys, or vice-versa */
function array_smear($a, $v2k = true) {
    $values = ($v2k) ? array_values($a) : array_keys($a);

    $a = array();
    foreach ($values as $v)
        $a[$v] = $v;

    return ($a);
}

array_smear takes an array, then a boolean specifying whether you want to
smear the values over into the keys (the default, and probably what you
usually want) or vice-versa.

So:
$a = array('a', 'b', 'c');

$x = array_smear($a);
// x == array('a' => 'a', 'b' => 'b', 'c' => 'c');

$y = array_smear($a, false);
// y == array(0 => 0, 1 => 1, 2 => 2);


13-Jun-2002 09:13

I am working on a project wherein I had to delete something from an array,
but I couldn't leave a hole in the array.
For example:
<?php
$myarray[0] = "test0";
$myarray[1] = "test1";
$myarray[2] = "test2";

unset($myarray[1]);
for($i=0;$i<count($myarray);$i++) {
echo $i." = ".$myarray[$i]."
"; } /* Outputs this: 0 = test0 1 = */ ?> Obviously, that doesn't work. ;) I won't explain why, but you can probably figure that out yourself. Anyway, I wrote a function to correct this problem: <?php function deleteandpush($array, $indice) { unset($array[$indice]); for($i=0;$i<count($array);$i++) { if(!isset($array[$i])) { $array[$i] = $array[$i+1]; unset($array[$i+1]); }; } return $array; } $myarray[0] = "test0"; $myarray[1] = "test1"; $myarray[2] = "test2"; $myarray[3] = "test3"; $myarray[4] = "test4"; $array = deleteandpush($myarray, 3); for($i=0;$i<count($array);$i++) { echo $i.":".$array[$i]."
"; } /* Outputs: 0:test0 1:test1 2:test2 3:test4 */ ?> Hope this helps someone.

spam (at) speedcapture . com
15-Jun-2002 01:50

I want to share a VERY usefull way to debug php and arrays:

just create a file like array.func.inc.php

paste the following code into the file.

// To make ANY array visible ...

function viewArray($arr)
{
    echo '<table cellpadding="0" cellspacing="0"
border="1">';
    foreach ($arr as $key1 => $elem1) {
        echo '<tr>';
        echo '<td>'.$key1.'&nbsp;</td>';
        if (is_array($elem1)) { extArray($elem1); }
        else { echo '<td>'.$elem1.'&nbsp;</td>'; }
        echo '</tr>';
    }
    echo '</table>';
}

function extArray($arr)
{
    echo '<td>';
    echo '<table cellpadding="0" cellspacing="0"
border="1">';
    foreach ($arr as $key => $elem) {
        echo '<tr>';
        echo '<td>'.$key.'&nbsp;</td>';
        if (is_array($elem)) { extArray($elem);	}
        else { echo
'<td>'.htmlspecialchars($elem).'&nbsp;</td>'; }
        echo '</tr>';
    }
    echo '</table>';
    echo '</td>';
}

close the file and include that file into any other php document. If u
want to check the content of an array just type viewarray($array);

webkid%webkid.com
19-Jun-2002 05:47

A painstakenly written function to add a "value" to a recursive
array using a pathlist (also in the format of an array):

function recurse($a,$rm,$k,$d){ if (sizeof($rm)==0){$a[$k]=$d;
return ($a);}
$sh=array_shift($rm); $a[$sh]=recurse ($a[$sh],$rm,$k,$d);
return ($a);}

Called like this: $ary=recurse($ary,
array("level1","level2","level3"),"key",$value);

So an array like
Array(
    [0] => a
    [1] => b
    [2] => c
    [d] => Array
        (   [0] => a
            [1] => b
            [c] => Array
                (   [0] => e
                    [1] => f
                    [2] => g
                    [3] => h
                    [i] => Array
                        (   [0] => n
                        ) ) ) )
Can become
Array(
    [0] => a
    [1] => b
    [2] => c
    [d] => Array
        (   [0] => a
            [1] => b
            [c] => Array
                (   [0] => e
                    [1] => f
                    [2] => g
                    [3] => h
                    [i] => Array
                        (   [0] => n
                            [key] => data
                        ) ) ) )
With the call 
$ary=recurse($ary,array("d","c","i"),"key","data");


21-Jun-2002 05:14

<?

$myarray = array();

$myarray[1] = 1;
$myarray[2] = 2;
$myarray[3] = 3;
$myarray[4] = 4;

// I want to move $myarray[2] to the 4th position.

$ordered_array = reposition($myarray, 2,4);

foreach($ordered_array as $key=>$value){
	echo "ordered_array[$key] = $value";
}

?>

// The output of this function will be:

ordered_array[1] = 1
ordered_array[2] = 4
ordered_array[3] = 2
ordered_array[4] = 3

<?

function reposition($myarray,$myarray_key,$newpos){

	$oldpos = $myarray[$myarray_key];

	foreach($myarray as $key=>$value){
		if($key==$myarray_key){
			$myarray[$key] = $newpos;
		}else{

			if($oldpos>=$newpos){  // It's moving up the array

				// Values following it will go down (lower position)

				if($myarray[$key]<=$oldpos && $myarray[$key]>=$newpos){
					$myarray[$key]++;
				}

			}else{	// It's moving down the array

				// Values preceding it will go up (higher position)

				if($myarray[$key]>=$oldpos && $myarray[$key]<=$newpos){
					$myarray[$key]--;
				}
			}
		}
	}
	return $myarray;
}

?>


07-Jul-2002 09:19

i have a problem and i'm hoping somebody could help me with it.
basically i have a form with multiple text input boxes.

the number of these increases...so the next <tr> would have
username2,comment2,date2,time2.And the nextone 3...and so on.

So when the data is posted it s saved as an array in $HTTP_POST_VARS.
what i would need to do is somehow create a function that would foreach
usernameX commentX dateX timeX do a mysql query:
UPDATE comments SET username='$username', comment='$comment',
date='$date', time='$time' where id=$key"
.
This way all of the fields would be updated with one post.oh yeah $id is
the X at the end of username,comment,date and time.
The only way i knew how to do it(since i know almost zero php.
1)
do a listing of the $HTTP_POST_VARS.
2)remove all instances of username comment date and time from the keys.and
there for get a listing 
1
1
1
1
2
2
2
2
...
then just check if the key wasn't allready done and if it wasn't extract
the username+key comment+key date+key and time+key values of of
$HTTP_POST_VARS, and update the database.
Basically i got everything out of the array so i can just get the X values
and call the array again.
Seems sort of stupid and a waste of time.
I'm 100% sure there is an easier way of doing it.With foreach or smth.But
everything i tried failed =).
anyone have any ideas what to do?
here is the so called code(well only the part that i think can be done
another way:
and yes the crap actually works:

this is the part of the code that basically does all the garbage i wrote
above:

while (list($key, $value) = each ($HTTP_POST_VARS)) {

$search = "/comment/";
$replacement = "";
$key = preg_replace($search, $replacement, $key);
$search = "/username/";
$replacement = "";
$key = preg_replace($search, $replacement, $key);
$search = "/date/";
$replacement = "";
$key = preg_replace($search, $replacement, $key);
$search = "/time/";
$replacement = "";
$key = preg_replace($search, $replacement, $key);

if($key!=$prev_key) {
if($key != "function" AND $key != "show") {
global $HTTP_POST_VARS;
$username = "username";
$username .= $key;
$comment = "comment";
$comment .= $key;
$date = "date";
$date .= $key;
$time = "time";
$time .= $key;
$username = $HTTP_POST_VARS["$username"];
$comment = $HTTP_POST_VARS["$comment"];
$date = $HTTP_POST_VARS["$date"];
$time = $HTTP_POST_VARS["$time"];

$query =  ("UPDATE comments SET username='$username',
comment='$comment', date='$date', time='$time' where id=$key");

$result = MYSQL_QUERY($query);
}
}
$prev_key = $key;

}

MYSQL_CLOSE();	

does anybody have an example of a code that can edit multiple rows and
columns at once?...like phpmyadmin.

add a note about notes
previousvirtualarray_change_key_casenext
Last updated: Tue, 16 Jul 2002
show source | credits | stats | mirror sites:  
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Sat Jul 20 08:32:23 2002 CEST