|
|
II. Fun��es para a manipula��o de arrays
Essas fun��es permitem a intera��o e manipula��o de arrays de
v�rias formas. Arrays s�o essenciais para armazenar, gerenciar,
operar sobre um conjunto de vari�veis.
Arras simples e multidimensionais (matrizes) s�o suportados, e podem
ser criados pelo usu�rio ou por outras fun��es.
Existem diversas fun��es espec�ficas para bancos de dados para preencher
arrays com os dados retornados em consultas, e v�rios outros tipos de fun��es
tamb�m retornam arrays.
Por favor, veja a se��o Arrays
do manual para uma explica��o mais detalhada sobre como arrays s�o
implementados e utilizados no PHP.
Veja tamb�m is_array(), explode(),
implode(), split()
e join().
- �ndice
- array_change_key_case -- Retorna um array com todas as chaves string em mai�sculo ou
min�sculo
- array_chunk -- Divide um array em peda�os
- array_count_values -- Conta todos os valores de um array
- array_diff -- Calcula as diferen�as entre arrays
- array_fill -- Preenche um array com valores
- array_filter --
Filtra os elementos de um array de acordo com uma fun��o
- array_flip -- Inverte a rela��es entre chaves e valores
- array_intersect -- Calcula a interse��o entre arrays
- array_key_exists -- Checa se uma chave existe num array
- array_keys -- Retorna todas as chaves de um array
- array_map --
Aplica uma fun��o em todos os elementos dos arrays dados
- array_merge_recursive -- Funde dois ou mais arrays recursivamente
- array_merge -- Funde dois ou mais arrays
- array_multisort -- Classifica m�ltiplos arrays ou multi-dimensionais
- array_pad --
Expande um array para um certo comprimento com um certo valor
- array_pop -- Retira um elemento do final do array
- array_push --
Adiciona um ou mais elementos no final de um array
- array_rand --
Pega um ou mais elementos aleat�rios do array
- array_reduce --
Reduz um array para um �nico elemento atrav�s de um processo iterativo
utilizando uma fun��o de callback.
- array_reverse --
Retorna um array com os elementos na ordem inversa
- array_search --
Procura por um valor em um array e retorna sua chave correspondente
caso seja encontrado
- array_shift --
Retira o primeiro elemento de um array
- array_slice -- Extrai uma "fatia" de um array
- array_splice --
Remove uma regi�o do array e substitui por outros elementos
- array_sum --
Calcula a soma dos elementos de um array
- array_unique -- Remove o valores duplicados de um array
- array_unshift --
Adiciona um ou mais elementos no in�cio de um array
- array_values -- Retorna todos os valores de um array
- array_walk --
Aplica uma determinada func�o em cada elemento de um array
- array --
Cria um array
- arsort --
Classifica um array em ordem descrescente mantendo a associa��o entre os
�ndices e os elementos
- asort --
Classifica um array mantendo a associa��o entre os �ndices e
os elementos
- compact --
Cria um array contendo vari�veis e seus valores
- count -- Conta o n�mero de elementos de uma vari�vel
- current -- Retorna o elemento corrente em um array
- each --
Retorna o par chave/valor corrente de um array e avan�a o seu cursor
- end --
Faz com que o ponteiro interno de um array aponte para o seu �ltimo
elemento
- extract --
Importa vari�veis para a tabela de s�mbolos a partir de um array
- in_array -- Retorna TRUE se um valor existe no array
- key -- Retorna uma chave de um array associativo
- krsort -- Classifica um array pelas chaves em ordem descrescente
- ksort -- Classifica um array pelas chaves
- list --
Cria vari�veis como se fossem arrays
- natcasesort --
Classifica um array utilizando o algoritmo da "ordem natural" sem
diferenciar mai�sculas e min�sculas
- natsort --
Classifica um array utlizando o algoritmo da "ordem natural"
- next --
Avan�a o ponteiro interno de um array
- pos -- Retorna o elemento atual do array
- prev -- Retrocede o ponteiro interno de um array
- range --
Cria um array contendo uma faixa de elementos
- reset --
Faz o ponteiro interno de um array apontar para o seu primeiro elemento
- rsort -- Classifica um array em ordem descrescente
- shuffle -- Mistura os elementos de um array
- sizeof -- Retorna o n�mero de elementos de uma vari�vel
- sort -- Classifica um array
- uasort --
Classifica um array utlizando uma fun��o de compara��o definida pelo usu�rio e mantendo
as associa��es dos �ndices
- uksort --
Classifica um array pelas chaves utilizando uma fun��o de compara��o
definida pelo usu�rio.
- usort --
Classifica um array pelos valores utilizando uma fun��o de compara��o
definida pelo usu�rio
User Contributed Notes Fun��es para a manipula��o de arrays |
|
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.' </td>';
if (is_array($elem1)) { extArray($elem1); }
else { echo '<td>'.$elem1.' </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.' </td>';
if (is_array($elem)) { extArray($elem); }
else { echo
'<td>'.htmlspecialchars($elem).' </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.
|
|
|
| |