уменьшить размер массива php
Массивы
User Contributed Notes 17 notes
For newbies like me.
Creating new arrays:-
//Creates a blank array.
$theVariable = array();
//Creates an array with elements.
$theVariable = array(«A», «B», «C»);
//Creating Associaive array.
$theVariable = array(1 => «http//google.com», 2=> «http://yahoo.com»);
//Creating Associaive array with named keys
$theVariable = array(«google» => «http//google.com», «yahoo»=> «http://yahoo.com»);
Note:
New value can be added to the array as shown below.
$theVariable[] = «D»;
$theVariable[] = «E»;
To delete an individual array element use the unset function
output:
Array ( [0] => fileno [1] => Array ( [0] => uid [1] => uname ) [2] => topingid [3] => Array ( [0] => touid [1] => Array ( [0] => 1 [1] => 2 [2] => Array ( [0] => 3 [1] => 4 ) ) [2] => touname ) )
when I hope a function string2array($str), «spam2» suggest this. and It works well
hope this helps us, and add to the Array function list
Another way to create a multidimensional array that looks a lot cleaner is to use json_decode. (Note that this probably adds a touch of overhead, but it sure does look nicer.) You can of course add as many levels and as much formatting as you’d like to the string you then decode. Don’t forget that json requires » around values, not ‘!! (So, you can’t enclose the json string with » and use ‘ inside the string.)
Converting a linear array (like a mysql record set) into a tree, or multi-dimensional array can be a real bugbear. Capitalizing on references in PHP, we can ‘stack’ an array in one pass, using one loop, like this:
$node [ ‘leaf’ ][ 1 ][ ‘title’ ] = ‘I am node one.’ ;
$node [ ‘leaf’ ][ 2 ][ ‘title’ ] = ‘I am node two.’ ;
$node [ ‘leaf’ ][ 3 ][ ‘title’ ] = ‘I am node three.’ ;
$node [ ‘leaf’ ][ 4 ][ ‘title’ ] = ‘I am node four.’ ;
$node [ ‘leaf’ ][ 5 ][ ‘title’ ] = ‘I am node five.’ ;
Hope you find it useful. Huge thanks to Nate Weiner of IdeaShower.com for providing the original function I built on.
If an array item is declared with key as NULL, array key will automatically be converted to empty string », as follows:
A small correction to Endel Dreyer’s PHP array to javascript array function. I just changed it to show keys correctly:
function array2js($array,$show_keys)
<
$dimensoes = array();
$valores = array();
Made this function to delete elements in an array;
?>
but then i saw the methods of doing the same by Tyler Bannister & Paul, could see that theirs were faster, but had floors regarding deleting multiple elements thus support of several ways of giving parameters. I combined the two methods to this to this:
?>
Fast, compliant and functional 😉
//Creating a multidimensional array
/* 2. Works ini PHP >= 5.4.0 */
var_dump ( foo ()[ ‘name’ ]);
/*
When i run second method on PHP 5.3.8 i will be show error message «PHP Fatal error: Can’t use method return value in write context»
array_mask($_REQUEST, array(‘name’, ’email’));
array_slice
(PHP 4, PHP 5, PHP 7, PHP 8)
array_slice — Выбирает срез массива
Описание
Список параметров
Обратите внимание, что параметр offset обозначает положение в массиве, а не ключ.
Возвращаемые значения
Возвращает срез. Если смещение больше длины массива, то будет возвращён пустой массив.
Примеры
Пример #1 Пример использования array_slice()
Результат выполнения данного примера:
Пример #2 Пример использования array_slice() с одномерным массивом
Результат выполнения данного примера:
Пример #3 Пример использования array_slice() с массивом из смешанных ключей
Результат выполнения данного примера:
Смотрите также
User Contributed Notes 19 notes
Array slice function that works with associative arrays (keys):
function array_slice_assoc($array,$keys) <
return array_intersect_key($array,array_flip($keys));
>
array_slice can be used to remove elements from an array but it’s pretty simple to use a custom function.
One day array_remove() might become part of PHP and will likely be a reserved function name, hence the unobvious choice for this function’s names.
$lunch = array(‘sandwich’ => ‘cheese’, ‘cookie’=>’oatmeal’,’drink’ => ‘tea’,’fruit’ => ‘apple’);
echo »;
?>
(remove 9’s in email)
Using the varname function referenced from the array_search page, submitted by dcez at land dot ru. I created a multi-dimensional array splice function. It’s usage is like so:
. Would strip blah4 from the array, no matter where the position of it was in the array ^^ Returning this.
Array ( [admin] => Array ( [0] => blah1 [1] => blah2 ) [voice] => Array ( [0] => blah3 ) )
?>
Check out dreamevilconcept’s forum for more innovative creations!
based on worldclimb’s arem(), here is a recursive array value removal tool that can work with multidimensional arrays.
function remove_from_array($array,$value) <
$clear = true;
$holding=array();
If you want an associative version of this you can do the following:
function array_slice_assoc($array,$keys) <
return array_intersect_key($array,array_flip($keys));
>
However, if you want an inverse associative version of this, just use array_diff_key instead of array_intersect_key.
function array_slice_assoc_inverse($array,$keys) <
return array_diff_key($array,array_flip($keys));
>
Array (
‘name’ = ‘Nathan’,
‘age’ = 20
)
Array (
‘age’ = 20,
‘height’ = 6
)
To save the sort order of a numeric index in the array. Version php =>5.5.26
/*
Example
*/
array_reorder($a,$order,TRUE);
echo »;
/** exemple end **/
?>
If you want to remove a specified entry from an array i made this mwethod.
$int = 3 ; //Number of entries in the array
$int2 = 0 ; //Starter array spot. it will begine its search at 0.
$del_num = 1 ; //Represents the second entry in the array. which is the one we will happen to remove this time. i.e. 0 = first entry, 1 = second entry, 2 = third.
I was trying to find a good way to find the previous several and next several results from an array created in a MySQL query. I found that most MySQL solutions to this problem were complex. Here is a simple function that returns the previous and next rows from the array.
Sometimes you need to pick certain non-integer and/or non-sequential keys out of an array. Consider using the array_pick() implementation below to pull specific keys, in a specific order, out of a source array:
Функции для работы с массивами
Содержание
User Contributed Notes 14 notes
A simple trick that can help you to guess what diff/intersect or sort function does by name.
Example: array_diff_assoc, array_intersect_assoc.
Example: array_diff_key, array_intersect_key.
Example: array_diff, array_intersect.
Example: array_udiff_uassoc, array_uintersect_assoc.
This also works with array sort functions:
Example: arsort, asort.
Example: uksort, ksort.
Example: rsort, krsort.
Example: usort, uasort.
?>
Return:
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Cuatro [ 4 ] => Cinco [ 5 ] => Tres [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
Array ( [ 0 ] => Cero [ 1 ] => Uno [ 2 ] => Dos [ 3 ] => Tres [ 4 ] => Cuatro [ 5 ] => Cinco [ 6 ] => Seis [ 7 ] => Siete [ 8 ] => Ocho [ 9 ] => Nueve [ 10 ] => Diez )
?>
Updated code of ‘indioeuropeo’ with option to input string-based keys.
Here is a function to find out the maximum depth of a multidimensional array.
// return depth of given array
// if Array is a string ArrayDepth() will return 0
// usage: int ArrayDepth(array Array)
Short function for making a recursive array copy while cloning objects on the way.
If you need to flattern two-dismensional array with single values assoc subarrays, you could use this function:
to 2g4wx3:
i think better way for this is using JSON, if you have such module in your PHP. See json.org.
to convert JS array to JSON string: arr.toJSONString();
to convert JSON string to PHP array: json_decode($jsonString);
You can also stringify objects, numbers, etc.
Function to pretty print arrays and objects. Detects object recursion and allows setting a maximum depth. Based on arraytostring and u_print_r from the print_r function notes. Should be called like so:
I was looking for an array aggregation function here and ended up writing this one.
Note: This implementation assumes that none of the fields you’re aggregating on contain The ‘@’ symbol.
While PHP has well over three-score array functions, array_rotate is strangely missing as of PHP 5.3. Searching online offered several solutions, but the ones I found have defects such as inefficiently looping through the array or ignoring keys.
array_reduce
(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)
array_reduce — Итеративно уменьшает массив к единственному значению, используя callback-функцию
Описание
array_reduce() итеративно применяет callback-функцию callback к элементам массива array и, таким образом, сводит массив к единственному значению.
Список параметров
Содержит значение текущей итерации.
Возвращаемые значения
Возвращает получившееся значение.
Примеры
Пример #1 Пример использования array_reduce()
Смотрите также
User Contributed Notes 17 notes
To make it clearer about what the two parameters of the callback are for, and what «reduce to a single value» actually means (using associative and commutative operators as examples may obscure this).
Sometimes we need to go through an array and group the indexes so that it is easier and easier to extract them in the iteration.
// add a son to his dad who has already been added
// by the first or second conditional «if»
//Grouping submenus to their menus
array (
0 =>
array (
‘menu_id’ => ‘1’,
‘menu_name’ => ‘Clients’,
‘submenu’ =>
array (
0 =>
array (
‘submenu_name’ => ‘Add’,
‘submenu_link’ => ‘clients/add’,
),
1 =>
array (
‘submenu_name’ => ‘List’,
‘submenu_link’ => ‘clients’,
),
),
),
1 =>
array (
‘menu_id’ => ‘2’,
‘menu_name’ => ‘Products’,
‘submenu’ =>
array (
0 =>
array (
‘submenu_name’ => ‘List’,
‘submenu_link’ => ‘products’,
),
),
),
)
So, if you were wondering how to use this where key and value are passed in to the function. I’ve had success with the following (this example generates formatted html attributes from an associative array of attribute => value pairs):
?>
This will output:
name=»first_name» value=»Edward»
You can reduce a two-dimensional array into one-dimensional using array_reduce and array_merge. (PHP>=5.3.0)
?>
//output:
middleware 2 begin:
middleware 1 begin.
Generate some response.
middleware 1 end.
middleware 2 end.
4
Adding diagnostic output to andFunc() shows that the first call to andFunc is with the arguments (NULL, true). This resolves to false (as `(bool) null == false`) and thereby corrupts the whole reduction.
So in this case I have to set `$initial = true` so that the first call to andFunc() will be (true, true). Now, if I were doing, say, orFunc(), I would have to set `$initial = false`. Beware.
I don’t honestly see why array_reduce starts with a null argument. The first call to the callback should be with arguments ($initial[0],$initial[1]) [or whatever the first two array entries are], not (null,$initial[0]). That’s what one would expect from the description.
If you want something elegant in your code, when dealing with reducing array, just unshift first element, and use it as initial, because if you do not do so, you will + first element with first element:
array_pop
(PHP 4, PHP 5, PHP 7, PHP 8)
array_pop — Извлекает последний элемент массива
Описание
Замечание: Эта функция при вызове сбрасывает указатель массива, переданного параметром.
Список параметров
Массив, из которого берётся значение.
Возвращаемые значения
Ошибки
При вызове этой функции с не массивом будет вызвана ошибка уровня E_WARNING.
Примеры
Пример #1 Пример использования array_pop()
Смотрите также
User Contributed Notes 16 notes
I wrote a simple function to perform an intersect on multiple (unlimited) arrays.
Pass an array containing all the arrays you want to compare, along with what key to match by.
will return a : Array ( [0] => )
so u can fix it using.
For the sake of array_unshift()
🙂
I had a problem when using this function because my array was made up entirley of numbers, so I have made my own function. Hopefully it will be useful to somebody.
Note that array_pop doesn’t issue ANY warning or error if the array is already empty when you try to pop something from it. This is bizarre! And it will cause cascades of errors that are hard to resolve without knowing the real cause.
Rather than an error, it silently returns a NULL object, it appears, so in my case I ended up with warnings elsewhere about accessing elements of arrays with invalid indexes, as I was expecting to have popped an array. This behaviour (and the lack of any warning, when many trivial things are complained about verbosely) is NOT noted in the manual above. Popping an already empty stack should definitely trigger some sort of notice, to help debugging.
Sure, it’s probably good practice to wrap the pop in an if (count($array)) but that should be suggested in the manual, if there’s no error returned for trying something that should fail and obviously isn’t expected to return a meaningful result.
alex.chacon@terra.com
Hi
Here there is a function that delete a elemente from a array and re calculate indexes
strrchr is a lot more useful than the other example using array_pop for finding the extension of a file. For example:
Notice that, you should assign a variable for function explode, then pass the variable reference into array_pop to avoid the Strict Standard warning.
@smp_info
I think you are still tired. What would be wrong with:
//$array == array(‘one’, ‘two’, ‘three’);
?>
As the documentation clearly notes, array_pop() not only returns the last element, but actually removes it from the array wich is passed by reference. Calling array_diff is a waste of resources.
Quick way to get the extension from a file name using array_pop: