|
|
II. 配列関数(array)
これらの関数により様々な手法で配列にアクセスし、操作することが可能
になります。配列は、変数の組を保存、管理、操作する基本的な要素です。
通常の配列および多次元配列がサポートされており、ユーザが定義したり、
他の関数で作成することも可能です。いくつかのデータベース処理関数は、
データベースのクエリから配列を返しますし、いくつかの関数は配列を返
します。
PHPでの配列の実装や使用方法の詳細については、マニュアルの
配列に関する節を参照下
さい。
これらの関数は、標準モジュールの一部として利用可能であり、常に使用できます。 これらの関数はPHPコアに含まれるため、使用す
る際にインストールは不要です。 この拡張モジュールは設定ディレクティブを全く定義しません。 この拡張モジュールはリソース型を全く定義しません。
この一覧にある定数は、PHPコアに含まれており常に利用可能です。
ソース順のフラグ:
ソート型のフラグ: 種々のソート関数で使用されます
- SORT_REGULAR
(integer)
SORT_REGULARは通常の比較するために使用され
ます。
- SORT_NUMERIC
(integer)
SORT_NUMERICは数値で比較を行うために使用さ
れます。
- SORT_STRING
(integer)
SORT_STRINGは文字列として比較を行うために使
用されます。
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) {
$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
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 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;
}
}
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
?>
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,"~"));
?>
--Phil
* not really sure if this is a glitch. here is what the manual says:
<?php ?>
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) {
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.
| |