PHP: Funkce pro pr�ci s poli - Manual
PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<virtualarray_change_key_case>
view the version of this page
Last updated: Thu, 15 Jul 2004

II. Funkce pro pr�ci s poli

�vod

Tyto funkce v�m umo��uj� manipulovat a interagovat r�zn�mi zp�soby s poli. Pole jsou nezbytn� pro ukl�d�n� a pr�ci se sadami prom�nn�ch.

Podporov�na jsou jednoduch� a v�cerozm�rn� pole; vytv��et se daj� u�ivatelsky i jako v�stup funkce. Existuj� datab�zov� funkce na pln�n� pol� v�sledky datab�zov�ch dotaz�, a n�kolik dal��ch funkc� vrac� pole.

Viz tak� ��st manu�lu pole pro detailn� popis toho, jak jsou pole v PHP implementov�ny a jak se pou��vaj�.

Po�adavky

Tyto funkce jsou k dispozici jako sou��st standardn�ho modulu, kter� je v�dy dostupn�.

Instalace

K pou��v�n� t�chto funkc� nen� t�eba ��dn� instalace, jsou sou��st� j�dra PHP.

Konfigurace b�hu

Toto roz���en� nem� definov�no ��dn� konfigura�n� direktivy.

Typy prost�edk�

Toto roz���en� nem� definov�n ��dn� typ prost�edku (resource).

P�eddefinovan� konstanty

Konstanty z tohoto seznamu jsou v�dy dostupn� jako sou��st j�dra PHP.

CASE_LOWER (integer)

CASE_LOWER is used with array_change_key_case() and is used to convert array keys to lower case. This is also the default case for array_change_key_case().

CASE_UPPER (integer)

CASE_UPPER is used with array_change_key_case() and is used to convert array keys to upper case.

Sorting order flags:

SORT_ASC (integer)

SORT_ASC is used with array_multisort() to sort in ascending order.

SORT_DESC (integer)

SORT_DESC is used with array_multisort() to sort in descending order.

Sorting type flags: used by various sort functions

SORT_REGULAR (integer)

SORT_REGULAR is used to compare items normally.

SORT_NUMERIC (integer)

SORT_NUMERIC is used to compare items numerically.

SORT_STRING (integer)

SORT_STRING is used to compare items as strings.

COUNT_NORMAL (integer)

COUNT_RECURSIVE (integer)

EXTR_OVERWRITE (integer)

EXTR_SKIP (integer)

EXTR_PREFIX_SAME (integer)

EXTR_PREFIX_ALL (integer)

EXTR_PREFIX_INVALID (integer)

EXTR_PREFIX_IF_EXISTS (integer)

EXTR_IF_EXISTS (integer)

EXTR_REFS (integer)

Obsah
array_change_key_case -- Returns an array with all string keys lowercased or uppercased
array_chunk -- Split an array into chunks
array_combine --  Creates an array by using one array for keys and another for its values
array_count_values -- Spo��tat v�echny hodnoty v poli
array_diff_assoc -- Computes the difference of arrays with additional index check
array_diff_uassoc --  Computes the difference of arrays with additional index check which is performed by a user supplied callback function
array_diff -- Spo��tat rozd�l pol�
array_fill -- Fill an array with values
array_filter --  Filters elements of an array using a callback function
array_flip -- Prohodit kl��e a hodnoty pole
array_intersect_assoc -- Computes the intersection of arrays with additional index check
array_intersect -- Spo��tat pr�nik pol�
array_key_exists -- Checks if the given key or index exists in the array
array_keys -- Vr�tit v�echny kl��e pole
array_map --  Applies the callback to the elements of the given arrays
array_merge_recursive -- Rekurzivn� slou�it dv� nebo v�ce pol�
array_merge -- Slou�it dv� nebo v�ce pol�
array_multisort -- T��dit v�ce pol�, nebo v�cerozm�rn� pole
array_pad -- Doplnit pole hodnotou na ur�enou d�lku
array_pop -- Odstranit prvek z konce pole
array_push -- P�idat jeden nebo v�ce prvk� na konec pole
array_rand -- Vybrat n�hodn� jeden nebo v�ce prvk� pole
array_reduce --  Iteratively reduce the array to a single value using a callback function
array_reverse -- Vr�tit pole s prvky v opa�n�m po�ad�
array_search --  Searches the array for a given value and returns the corresponding key if successful
array_shift -- Odstranit prvek ze za��tku pole
array_slice -- Vyt�hnout ��st pole
array_splice -- Odstranit ��st pole a nahradit ji n���m jin�m
array_sum --  Calculate the sum of values in an array.
array_udiff_assoc -- Computes the difference of arrays with additional index check. The data is compared by using a callback function.
array_udiff_uassoc -- Computes the difference of arrays with additional index check. The data is compared by using a callback function. The index check is done by a callback function also
array_udiff -- Computes the difference of arrays by using a callback function for data comparison.
array_unique -- Odstranit z pole duplicitn� hodnoty
array_unshift -- P�ipojit jeden nebo v�ce prvk� na za��tek pole
array_values -- Vr�tit v�echny hodnoty v poli
array_walk_recursive --  Apply a user function recursively to every member of an array
array_walk -- Pou��t u�ivatelskou funkci na v�echny prvky pole
array --  Vytvo�it pole
arsort -- T��dit pole sestupn� se zachov�n�m kl���
asort -- T��dit pole se zachov�n�m index�
compact -- Vytvo�it pole obsahuj�c� prom�nn� a jejich hodnoty
count -- Spo��tat prvky v prom�nn�
current -- Vr�tit sou�asn� prvek pole
each --  Vrac� dal�� kl��/hodnota p�r z pole
end --  Nastavit vnit�n� ukazatel pole na jeho posledn� prvek
extract -- Importovat prom�nn� z pole do symbolov� tabulky
in_array -- Ov��it, zda v poli existuje dan� hodnota
key -- Fetch a key from an associative array
krsort -- T��dit pole sestupn� podle kl���
ksort -- T��dit pole podle kl���
list -- P�i�adit hodnoty p�om�nn�m jako kdyby byly polem
natcasesort --  T��dit pole s vyu�it�m algoritmu "p�irozen�ho t��d�n�" (case-insensitive)
natsort --  T��dit pole s vyu�it�m algoritmu "p�irozen�ho t��d�n�"
next -- Posunout intern� ukazatel pole
pos -- Z�skat sou�asn� prvek pole
prev -- Rewind intern� ukazatel pole
range -- Vytvo�it pole obsahuj�c� rozsah integer�
reset -- Nastavit intern� ukazatel pole na jeho prvn� prvek
rsort -- T��dit pole sestupn�
shuffle -- Zam�chat pole
sizeof -- Zjistit po�et prvk� v poli
sort -- T��dit pole
uasort --  T��dit pole pomoc� u�ivatelsky definovan� porovn�vac� funkce se zachov�n�m kl���
uksort --  T��dit pole podle kl��� pomoc� u�ivatelsky definovane porovn�vac� funkce
usort --  T��dit pole podle hodnot pomoc� u�ivatelsky definovan� porovn�vac� funkce


add a note add a note User Contributed Notes
Funkce pro pr�ci s poli
27-Oct-2004 10:29
/*! \fn array_renamekeys($values, $table)
   *  \brief Renames the array keys of an array
   *
   *  $table = array ( "<old_value" => "new_value", ... )
   */
   function array_renamekeys($values, $table)
   {
     if (is_array($values))
     {
         foreach($values as $k => $v)
         {
           if (strlen($table["$k"])>0)
           {
               unset($values["$k"]);
               $k=$table["$k"];
           }

           if (is_array($v))
           {
               $values["$k"]=$this->array_renamekeys($v, $table);
           }
           else
           {
               $values["$k"]=$v;
           }
         }
     }
     return $values;
   }
skopek at mediatac dot com
13-Oct-2004 10: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) {
  
  
//returned array...
  
$cartesic = array();
  
  
//calculate expected size of cartesian 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);   
       }
      
//set cursor on next element in the arrays, beginning with the last array
      
for($j=(sizeof($arrays)-1);$j>=0;$j--)
       {
          
//if next returns true, then break
          
if(next($arrays[$j])) {
               break;
           } else {   
//if next returns false, then reset and go on with previuos array...
              
reset($arrays[$j]);
           }
       }
   }
   return
$cartesic;
}
//example
$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
hadi_rastgou at yahoo dot com
11-Oct-2004 04:57
A recursive function for TRNSFORMING  nested arrays to a STRING:

#This recursive function transforms array indexs
#and their vlaues to a string

function array_to_str($array){
   $str_of_array_keys_n_vals = "";
   foreach($array as $key=>$val){
       if(is_array($val)){
           $str_of_array_keys_n_vals .= "[$key = {". array_to_str($val)."}] , ";
       }
       else{
           $str_of_array_keys_n_vals .= "[$key=$val] , ";
       }
   }
  
   return substr($str_of_array_keys_n_vals, 0, strlen($str_of_array_keys_n_vals)-3);
}

Array (
   [ou] => My Test
   [description] => ee
   [objectclass] => Array (
                     [0] => top
                     [1] => organizationalunit
                               )
       )

Will be

[ou=My Test] , [description=ee] , [objectclass = {[0=top] , [1=organizationalunit]}]
reverse esacdaehasinhoj at oohay dot moc
28-Jun-2004 10:39
I've included a neat function I had to hack out, to handle exploding on multiple strings as tokens without losing which token created the break.  There's lots of room for improvement; this function has bad behavior when tokens overlap, for instance, and doesn't provide any way to discover what tokens occurred in what order (though, token order for a given delimiter is preserved.)  Should there be a piece of string before any delimiters, or should there be no delimiter, the remainder will be stored in the result's index for null string.

Case sensitivity control is dependant on stripos(), which is only available in PHP5 CVS.  PHP<5 may only use this function case sensitively unless a replacement is provided.

<?php

 
// function has incorrect results when delimiters overlap
 
function mexplode_dangerous($delimiters, $data, $casesensitive = true) {
    
$points = array();
     foreach (
$delimiters as $delim) {
        
$nextpoint = 0;
         if (
$casesensitive) {
               while (!( (
$point = strpos($data, $delim, $nextpoint)) === false )) {
                  
$points[$point] = $delim;
                  
$nextpoint = $point + strlen($delim);
               }
         } else {
               while (!( (
$point = stripos($data, $delim, $nextpoint)) === false )) {
                  
$points[$point] = $delim;
                  
$nextpoint = $point + strlen($delim);
               }
         }
     }

     if (
count($points) == 0) {

         return array(
'' => $data);

     } else {

        
$start=strlen($data);
        
reset($points);
        
krsort($points);

         while (
$point = current($points)) {
            
$offset = key($points) + strlen($point);
            
$result[$point][] = substr($data, $offset, $start-$offset);
            
$start=key($points);
            
next($points);
         }

        
reset($result);
         while(
$row = current($result)) {
            
$output[key($result)] = array_reverse($row);
            
next($result);
         }

        
$output['']=substr($data,0,$start);

         return
$output;

     }
  }

 
// Usage is fairly straightforward.

 
print_r(mexplode_dangerous(array('@','=','::','|'), 'hello@at1=eq1::colon1|pipe1|pipe2|pipe3::colon2::colon3=eq2@at2'));

?>

This should return:

Array
(
   [@] => Array
       (
           [0] => at1
           [1] => at2
       )

   [=] => Array
       (
           [0] => eq1
           [1] => eq2
       )

   [::] => Array
       (
           [0] => colon1
           [1] => colon2
           [2] => colon3
       )

   [|] => Array
       (
           [0] => pipe1
           [1] => pipe2
           [2] => pipe3
       )

   [] => hello
)
brooklynphil hotmail com
21-Jun-2004 10:19
was browsing, and saw some array flattening functions... then i remembered i wrote one a while ago, and i wanted to compare code. to my surprise, the code was basically the same, except my code preserves keys:
<?php function array_flatten(&$a,$pref='') {
  
$ret=array();
   foreach (
$a as $i => $j)
       if (
is_array($j))
          
$ret=array_merge($ret,array_flatten($j,$pref.$i));
       else
          
$ret[$pref.$i] = $j;
   return
$ret;
   }
?>

the flattened array will have its numerical keys converted to strings, however, due to a glitch* in php, these string keys might be converted back to integers!

<?php $qqq= array(array(array(12)),array(56),array(14,1));
pretty($qqq);
pretty(array_flatten($qqq));?>

will render:

<?php
/*array(3){[0]=>array(1){[0]=>array(1){[0]=>int(12)}}
[1]=>array(1){[0]=>int(56)  }
[2]=>array(2){[0]=>int(14)
   [1]=>int(1)}
}
array(4) {  ["000"]=>  int(12)
  [0]=>  int(56)
  [1]=>  int(14)
  [2]=>  int(1)}*/
?>

as you can see the firsrt array 'tree' is flattened successfully, because "000" does not convert to 0, but the subsequent 'tree's are converted from e.g. "10" to 0... (why 0? i would have thought 10)

seeding the prefix with something that forces a string conversion, alleviates this problem (and shows that its not my code, per se):

<?php
var_dump
(array_flatten($qqq,"~"));
/*array(4) {
  ["~000"]=>  int(12)
  ["~10"]=>  int(56)
  ["~20"]=>  int(14)
  ["~21"]=>  int(1)}*/
?>

--Phil

* not really sure if this is a glitch.  here is what the manual says:
<?php /* A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). There are no different indexed and associative array types in PHP; there is only one array type, which can both contain integer and string indices. */ ?>
in
is there any way to circumvent this behaviour and force string keys? ive tried casting to no avail...
Minots Estich� <minots at d0x dot de>
22-May-2004 05:10
Sometimes it�s usefull to trim all values from a given array.
I wrote this function ( array_trim ) to do it for me:

<?php
function array_trim(&$arr)
{
  while (list(
$key,$val)=each($arr)):
   if ( (
strtoupper($key) != $key or ''.intval($key) == "$key") && $key != "argc" and $key != "argv"):
       if (
is_string($val)):
          
$arr[$key] = trim($val);
       endif;
       if (
is_array($val)):
          
$arr[$key] = array_trim($val);
       endif;
   endif;
  endwhile;
  return
$arr;
}
?>

If there is a better way, feel free to send me a note via
feedback-formular at .
gigi at orsone dot com
25-Apr-2004 05:30
Here is a small function to "convert" php arrays to javascript...
<?php
$menuz
=
  array(
'Products', 'products.php',
   array(
'Fruit', null,
         array(
'Bananas', 'products.php?cat=bananas'),
         array(
'Apples', 'products.php?cat=apples'),
         array(
'Lemons', 'products.php?cat=lemons')
       ),
       array(
'Chocolate', 'products.php?cat=chocolate')
  );

 
function
array_php2js($data) {
  foreach(
$data as $k=>$datum) {
   if(
is_null($datum)) $data[$k] = 'null';
   if(
is_string($datum)) $data[$k] = "'" . $datum . "'";
   if(
is_array($datum)) $data[$k] = php2js($datum);
  }
  return
"[" . implode(', ', $data) . "]";
}
print(
array_php2js($menuz));
?>

And you get:

['Products', 'products.php', ['Fruit', null, ['Bananas', 'products.php?cat=bananas'], ['Apples', 'products.php?cat=apples'], ['Lemons', 'products.php?cat=lemons']], ['Chocolate', 'products.php?cat=chocolate']]
I find it useful in many situation... ;)
esbjorn
22-Apr-2004 12:18
A shorter recursive function to flatten nested arrays could be:

function flattenArray($array)
{
   $flatArray = array();
   foreach( $array as $subElement ) {
       if( is_array($subElement) )
           $flatArray = array_merge($flatArray, flattenArray($subElement));
       else
           $flatArray[] = $subElement;
   }
   return $flatArray;
}
davidj at boundlessgallery dot DISLIKESPAM dot com
02-Apr-2004 01: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
)
webmaster at pzfn dot com
16-Mar-2004 03:15
You should be able to do this....

<?
function unset_by_val($needle,&$haystack) {
 
$haystack = array_flip($haystack);
  unset(
$haystack[$needle]);
 
$haystack = array_flip($haystack);
  return
$haystack;
}
?>
31-Jan-2004 10:54
unset($bar['mushroomsoup']) only works it the key
is 'mushroomsoup'.If you want to erase elements
of an array identified by values rather than by keys
you can use this function:
<?
function unset_by_val($needle,&$haystack) {
# removes all entries in array $haystack,
# who's value is $needle
 
while(($gotcha = array_search($needle,$haystack)) > -1)
   unset(
$haystack[$gotcha]);
}
 
$ring = array('gollum','smeagol','gollum','gandalf',
                    
'deagol','gandalf');
 
print_r($ring); echo "<br>";
 
unset_by_val('gollum',$ring);
 
print_r($ring);
?>
Will output:
Array ( [0] => gollum [1] => smeagol [2] => gollum
  [3] => gandalf [4] => deagol [5] => gandalf )
Array ( [1] => smeagol [3] => gandalf
  [4] => deagol [5] => gandalf )
31-Jan-2004 09:29
To remove an element from an array use unset(). Example:
unset($bar['mushroomsoup']);
28-Aug-2003 01: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 12: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 08: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.

<virtualarray_change_key_case>
 Last updated: Thu, 15 Jul 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2004 The PHP Group
All rights reserved.
This unofficial mirror is operated at: /
Last updated: Sun Nov 14 23:09:54 2004 Local time zone must be set--see zic manual page