PHP Add element to every sub array of multi dimension array
Whatever speed one might hope to gain by using array_walk, is lost with function overhead. Since you stated in your comments that the array is a result of a db query, you can simply include the bag
value in your result set by adding SELECT 'bag' AS 'type'
to your SQL statement.
$start = 0; $end = 0;
$orig = array(
array('id' => 1, 'title' => 'title 1'),
array('id' => 10, 'title' => 'title 10'),
array('id' => 11, 'title' => 'title 11')
);
// A
$start = microtime(true);
for ($a=0; $a<1000; $a++) {
$els1 = $orig;
array_walk($els1, function(&$val, $key){$val['type'] = 'bag';});
}
$end = microtime(true);
echo 'A: ', $end - $start, "<br />\n";
// B
$start = microtime(true);
for ($b=0; $b<1000; $b++) {
$els2 = $orig;
foreach ($els2 as &$el) {
$el['type'] = 'bag';
}
unset($el);
}
$end = microtime(true);
echo 'B: ', $end - $start, "<br />\n";
/* output:
A: 0.0076138973236084
B: 0.0047528743743896
A: 0.0075309276580811
B: 0.0045361518859863
A: 0.0075531005859375
B: 0.062379837036133
A: 0.0075340270996094
B: 0.0044951438903809
A: 0.0074868202209473
B: 0.0044751167297363
A: 0.0076088905334473
B: 0.0048189163208008
*/
how to push onto a sub-array of a multidimensional array?
I would start with putting all input information in an array so you know what to loop:
$old = array(
'brands' => Array (1=>a, 2=>b),
'titles' => Array (1=>d, 2=>e)
// etc
);
And then do a double loop:
$new = array();
foreach($old as $key => $value)
{
foreach ($value as $num_key => $content)
{
$new[$num_key][$key] = $content;
}
}
An additional advantage is that you preserve your original array keys.
PHP add elements to multidimensional array with array_push
if you want to add the data in the increment order inside your associative array you can do this:
$newdata = array (
'wpseo_title' => 'test',
'wpseo_desc' => 'test',
'wpseo_metakey' => 'test'
);
// for recipe
$md_array["recipe_type"][] = $newdata;
//for cuisine
$md_array["cuisine"][] = $newdata;
this will get added to the recipe or cuisine depending on what was the last index.
Array push is usually used in the array when you have sequential index: $arr[0] , $ar[1].. you cannot use it in associative array directly. But since your sub array is had this kind of index you can still use it like this
array_push($md_array["cuisine"],$newdata);
Get a sub array from multidimensional array using php
Write a recursive function for this. do foreach
and check array key with passed key, if matched return array. if not matched and check array value if it is an array with is_array()
, if yes, call function again, else return value
function getData($categoryArray, $key){
foreach($categoryArray as $k => $value){
if($k==$key) return $value;
if(is_array($value)){
$find = getData($value, $key);
if($find){
return $find;
}
}
}
return null;
}
$result1 = getData($category, 'Show Balance');
var_dump($result1);
$result = getData($category, 'Recharge');
var_dump($result);
Demo
sum values in sub array
You could run your values through array_sum
using array_map
$array = array_map('array_sum', $array);
All in all, something like -
$rows = [
['name' => 'name1', 'from' => 4, 'to' => 3],
['name' => 'name1', 'from' => 32, 'to' => 20],
['name' => 'name1', 'from' => 999, 'to' => 989],
['name' => 'name2', 'from' => 10.25, 'to' => 10],
['name' => 'name2', 'from' => 10.55, 'to' => 10],
['name' => 'name2', 'from' => 10.35, 'to' => 10],
['name' => 'name2', 'from' => 5, 'to' => 0],
];
$array = [];
foreach ($rows as $row) {
$array[$row['name']][] = $row['from'] - $row['to'];
}
print_r($array); // what you have so far
$array = array_map('array_sum', $array);
print_r($array); // what you want
See https://www.tehplayground.com/paAkQ8riS5KwFSfP
Although a better solution would be to add these as you go, like
$array = [];
foreach ($rows as $row) {
$array[$row['name']] += $row['from'] - $row['to'];
}
print_r($array);
See https://www.tehplayground.com/kA2QDWUluJ53Ueia
Add more elements in php array
One long way without using a loop :)
$array2 = array_fill(0, count($array1), ['import_id' => 10, 'country_id' => 1]);
$array2 = array_replace_recursive($array2, $array1);
demo
Find for each sub array in multidimensional array, if element on fixed position is highest value for this sub array
Determining the maximum using max
only properly works for integers, so I would use array_map
with hexdec
to achieve that.
Then all it needs is a comparison of the value at position 1 with that maximum, and if they are the same, then the index gets added to the result array:
$result = [];
foreach($hex_splited as $key => $value) {
if(hexdec($value[1]) == max(array_map('hexdec', $value))) {
$result[] = $key;
}
}
var_dump($result);
This gets you 0, 1, 3
as result. (As IMHO it should be, according to your stated requirements - the value 00
at position 1 in the first sub-array is also the maximum of all values in that sub-array. If you need to exclude 0 values, then you’ll have to modify accordingly.)
EDIT:
if all elements are equal, then return nothing
Okay, that can also be implemented quite easily - we use array_count_values
, and if the count of that is only 1, then that means all the elements had the exact same value.
So then it becomes
foreach($hex_splited as $key => $value) {
if(count(array_count_values($value)) != 1 &&
hexdec($value[1]) == max(array_map('hexdec', $value))) {
$result[] = $key;
}
}
With that, you get [1, 3]
as $result here.
Adding arrays to multi-dimensional array within loop
This is because array_merge
is not the right operation for this situation. Since all the $playerdata
arrays have the same keys, the values are overridden.
You want to use array_push
to append to an array. This way you will get an array of $playerdata
arrays.
array_push($allplayerdata, $playerdata);
Which is equivalent to adding an element with the square bracket syntax
$allplayerdata[] = $playerdata;
array_merge
- Merge one or more arraysarray_push
- Push one or more elements onto the end of array- Creating/modifying with square bracket syntax
Related Topics
Strip All HTML Tags, Except Allowed
Executing MySQLi_Query Inside a Function
How to Alias a Table in Laravel Eloquent Queries (Or Using Query Builder)
How to Access the PHP.Ini File in Godaddy Shared Hosting Linux
How to Increment Letters Like Numbers in PHP
How to Generate Random 64-Bit Value as Decimal String in PHP
Using Wildcards in Prepared Statement - MySQLi
Beautiful Way to Remove Get-Variables with PHP
PHP Remove Special Character from String
Post Form and Update Multiple Rows with MySQL
Php7.1 JSON_Encode() Float Issue
Why Use $_Server['Php_Self'] Instead of ""
How to Increase Memory Limit for PHP Over 2Gb
Laravel 5.4 on PHP 7.0: Pdo Exception - Could Not Find Driver (Mysql)