Adding 'simple' array elements to multidimensional array one-after-another PHP [duplicate] - php

This question already has answers here:
Push elements from one array into rows of another array (one element per row)
(4 answers)
Closed 5 months ago.
Problem: I want to add the values of Array2 one-after-another to a multidimensional array (array1).
Array 1:
Array
(
[0] => Array
(
[date] => 2020-01-01
[itemsSold] => 25.00000000
)
[1] => Array
(
[date] => 2020-01-02
[itemsSold] => 50.00000000
)
[2] => Array
(
[date] => 2020-01-03
[itemsSold] => 25.00000000
)
)
Array2:
Array
(
[0] => 10
[1] => 15
[2] => 25
)
Goal:
Array
(
[0] => Array
(
[date] => 2020-01-01
[itemsSold] => 25.00000000
[0] => 10
)
[1] => Array
(
[date] => 2020-01-02
[itemsSold] => 50.00000000
[0] => 15
)
[2] => Array
(
[date] => 2020-01-03
[itemsSold] => 25.00000000
[0] => 25
)
)
I am just learning programming since january 2021 so my best solution I got was this:
foreach ($array1 as $main => $value) {
foreach ($array2 as $sec => $entry) {
$array1[$main][] = $array2[$sec];
}
}
print_r($array1);
Output:
Array
(
[0] => Array
(
[date] => 2020-01-01
[itemsSold] => 25.00000000
[0] => 10
[1] => 15
[2] => 25
)
[1] => Array
(
[date] => 2020-01-02
[itemsSold] => 50.00000000
[0] => 10
[1] => 15
[2] => 25
)
[2] => Array
(
[date] => 2020-01-03
[itemsSold] => 25.00000000
[0] => 10
[1] => 15
[2] => 25
)
)
What am I doing wrong in my loop?? How can I get the values of array2 one-by-one into array1??
Thanks for any help ;)

The issue with your code is that you have nested a loop within another when you do not need to. Instead, use the loop format foreach ($array1 as $key => $value) so you can capture its index in $key, then use that as an index to $array2.
foreach ($array1 as $key => $value) {
// Append from $array2 by its index $key
// Using [] will append at index [0]
// You can modify $array1 inside the loop if you
// target it by $key. Notice that we are not using
// $value at all in this loop - only the $key matters.
$array1[$key][] = $array2[$key];
}
print_r($array1);
foreach also allows you to modify the value directly if you use a & reference. This is a little bit shorter:
foreach ($array1 as $key => &$value) {
// Looping over references to $array1 sub-arrays
// means that $value can be modified directly
$value[] = $array2[$key];
}
print_r($array1);
Iteration by reference is described in the PHP foreach manual

Related

Php how to create custom array using 2 arrays

I need some help on below array formation. I want to create a custom array using 2 arrays.
This is my first array :-
Array
(
[0] => Array
(
[0] => 26
[1] => 0.0000000000000000
)
[1] => Array
(
[0] => 25
[1] => 0.0000000000000000
)
[2] => Array
(
[0] => 24
[1] => 0.0000000000000000
)
)
This is my second array :-
Array
(
[0] => Array
(
[0] => 24
)
[1] => Array
(
[0] => 26
)
)
I want final array as below. Can someone please suggest how to form this array.
Array
(
[0] => Array
(
[0] => 26
[1] => 0.0000000000000000
)
[2] => Array
(
[0] => 24
[1] => 0.0000000000000000
)
)
I have used below but I want it without foreach.
$finalArray = array();
foreach ($secondArray as $key => $value) {
$key = array_search($value[0], array_column($firstArray, 0));
$finalArray[] = $firstArray[$key];
}
You can use array_filter():
$finalArray = array_filter($firstArray,
fn($item) => in_array($item[0], array_column($secondArray, 0))
);
It could be more efficiant to compute allowed values first:
$allowedValues = array_column($secondArray, 0);
$finalArray = array_filter($firstArray, fn($item) => in_array($item[0], $allowedValues));
Before PHP 7.4, you have to use use() to pass variable to the anonymous function:
$finalArray = array_filter($firstArray,
function($item) use($secondArray) {
return in_array($item[0], array_column($secondArray, 0));
}
);

I want to change the key of multidimensional array [duplicate]

This question already has answers here:
How do you reindex an array in PHP but with indexes starting from 1?
(12 answers)
Closed 3 years ago.
I want to change the key of the multidimensional array. the array contains key like 1,15,23,45 which should be replaced by normal index key like 0,1,2,3. I tried with below code. Something is missing in below code. Please, anyone, suggest to me.
$keys = array_keys($data);
$d = 0;
foreach($data as $row){
$key_data[$d] = $data[$keys[$d]];
unset($row[$keys[$d]]);
$d++;
}
Current Output
Array
(
[15] => Array
(
[0] => Array
(
[app_dealer_id] => 15
[dealer_name] => Sharad Thombre
[shopname] => Shivshankar Fertilizer
[contact_num] => 9049121143
[district] => Parbhani
)
)
[18] => Array
(
[0] => Array
(
[app_dealer_id] => 18
[dealer_name] => Gajanan Khapre
[shopname] => Shreyas Krishi Kendra
[contact_num] => 8007791946
[district] => Parbhani
)
)
)
Expected Output:
Array
(
[0] => Array
(
[0] => Array
(
[app_dealer_id] => 15
[dealer_name] => Sharad Thombre
[shopname] => Shivshankar Fertilizer
[contact_num] => 9049121143
[district] => Parbhani
)
)
[1] => Array
(
[0] => Array
(
[app_dealer_id] => 18
[dealer_name] => Gajanan Khapre
[shopname] => Shreyas Krishi Kendra
[contact_num] => 8007791946
[district] => Parbhani
)
)
)
use array_values()
$array = array_values($array);
Output:-https://3v4l.org/cUAdl
From php.net :
array_values() returns all the values from the array and indexes the array numerically.
So just add it after your loop to reindex you array :
$keys = array_keys($data);
$d = 0;
foreach($data as $row){
$key_data[$d] = $data[$keys[$d]];
unset($row[$keys[$d]]);
$d++;
}
$newArray = array_keys($key_data);

Sum values in multidimensional array by key [duplicate]

This question already has answers here:
Group array data on one column and sum data from another column
(5 answers)
Closed 1 year ago.
I have read a lot of answers here on SO but havent been able to sort this out.
I have multidimensional array that looks like this:
Array
(
[0] => Array
(
[0] =>
[1] => 655
)
[1] => Array
(
[0] => IT-82
[1] => 14
)
[2] => Array
(
[0] => IT-21
[1] => 5
)
[3] => Array
(
[0] => IT-82
[1] => 7
)
[4] => Array
(
[0] =>
[1] => 3
)
[5] => Array
(
[0] => IT-21
[1] => 4
)
[6] => Array
(
[0] =>
[1] => 3
)
[7] => Array
(
[0] => IT-21
[1] => 3
)
[8] => Array
(
[0] => IT-72
[1] => 7
)
[9] => Array
(
[0] => IT-75
[1] => 22
)
[10] => Array
(
[0] => IT-75
[1] => 3
)
)
I would like to sum the values according to the keys ending with a single array like:
Array
(
=> 661
IT-82 => 21
IT-21 => 12
IT-82 => 12
IT-72 => 7
IT-75 => 25
)
Tried with
foreach ($array as $k=>$subArray) {
foreach ($subArray as $id=>$value) {
$sumArray[$id]+=$value;
}
}
but this only returned the sum of all the values.
Any help appreciated.
Try:
$sumArray = array();
foreach ($array as $k=>$subArray) { //loop through array
if(isset($sumArray[$subArray[0]]))
$sumArray[$subArray[0]] += $subArray[1]; // set 0th index as key and 1st as value and add value to current index
else
$sumArray[$subArray[0]] = $subArray[1];
}
print_r($sumArray);
Output:
Array
(
[] => 661
[IT-82] => 21
[IT-21] => 12
[IT-72] => 7
[IT-75] => 25
)
I suppose it should be:
foreach ($array as $subArray) {
$sumArray[$subArray[0]] += $subArray[1];
}

running for loop on array without incremental index

I have this arbitrary multi dimensional array.
Array (
[0] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[5] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[10] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[15] => Array
(
[0] => 0
[1] => 1
[2] => 2
)
[1] => Array
(
[0] => 2
[1] => 1
[2] => 2
)
[2] => Array
(
[0] => 2
[1] => 1
[2] => 2
)
)
I wanna run a for loop to extract the data of each subarray.
But I cannot do a simple for loop because the index (0,5,10,15,1) is arbitrary.
Is there a way to run a for loop then skip the sub array if it is empty?
Thanks!
This will take $array and loop though it, echoing the keys.
You have an array in an array, you can place a foreach in a foreach:
// First we take the main array ($array) and loop though its values
foreach( $array as $main_key =>$sub_array){
echo $main_key.": <br />\n"; // echo the key, some extra html to format
// the values of the mainarray are arrays themselves, just loop again:
foreach($subarray as $sub_key =>$subvalue){
echo '- '.$subvalue."<br />\n";
}
}
There's a bit of a trap here if you foreach in a foreach:
foreach($array as $key =>$value){
foreach($value as $key=>$value){ /* ... */; }
}
This will create very weird results. The inner foreach uses the same parameter-names and will mess everything up.

Remove item from multidimensional array php

Here is the array:
[cart] => Array
(
[ProductId] => Array
(
[0] => P121100001
[1] => P121100002
)
[SellerId] => Array
(
[0] => S12110001
[1] => S12110001
)
[SpecifyId] => Array
(
[0] => 1
[1] => 2
)
[Quantity] => Array
(
[0] => 1
[1] => 1
)
[Price] => Array
(
[0] => 12
[1] => 29
)
[TotalPrice] => 41
)
I have the ProductId and I want to remove all the other items matching P121100002's key.
Is there an easy way to do this I can't can seem to come up with one?
You can loop through the full array and use unset() to, well, "unset" the specified index:
$index = array_search($cart['ProductId'], 'P121100002');
if ($index !== false) {
foreach ($cart as $key => $arr) {
unset($cart[$key][$index]);
}
}
The slight caveat to this approach is that it may disrupt your index orders. For instance, say you have:
[ProductId] => Array (
[0] => P121100001
[1] => P121100002
[2] => P121100003
)
And you want to remove P121100002, which has a corresponding index of 1. Using unset($cart['ProductId'][1]) will cause your array's to become:
[ProductId] => Array (
[0] => P121100001
[2] => P121100003
)
This may be something to remain concerned with if you're going to use a for loop to iterate through in the future. If it is, you can use array_values() to "reset" the indexes in the unset() loop from above:
foreach ($cart as $key => $arr) {
unset($cart[$key][$index]);
$cart[$key] = array_values($cart[$key]);
}
foreach($yourArray['ProductId'] as $key => $value) {
if ($value == $productIdToRemove) {
foreach($yourArray as $deleteKey => $deleteValue) {
unset($yourArray[$deleteKey][$key]);
}
break;
}
}
Use array_key_exists along with the unset() function

Categories