Adding Array of values to a multidimentional Array in PHP - php

I would like to add values from a $secondArray to $firstArray:
$firstArray = [
0 => [
'prodID' => 101,
'enabled' => 1,
],
1 => [
'prodID' => 105,
'enabled' => 0,
],
];
The $secondArray will always have the same amount of array items and will be in the same order as the $firstArray:
$secondArray = [34, 99];
This is what I have tried but I keep getting the wrong stockQT values after the exercise:
foreach ($secondArray as $value) {
foreach ($firstArray as &$firstArray) {
$firstArray['stockQT'] = $value;
}
}
Incorrect Result for a var_dump($firstArray):
array (size=2)
0 =>
array (size=3)
'prodID' => int 101
'subscribed' => int 1
'stockQT' => int 99
1 =>
array (size=3)
'prodID' => int 105
'subscribed' => int 0
'stockQT' => int 99
I have looked at similar posts but cant seem to get the correct vales after using different suggestions like while() loops. Below is what I need the $firstArray to look like:
array (size=2)
0 =>
array (size=3)
'prodID' => int 101
'subscribed' => int 1
'stockQT' => int 34
1 =>
array (size=3)
'prodID' => int 105
'subscribed' => int 0
'stockQT' => int 99

You just need one foreach() using the key since $secondArray will always have the same amount of array items and will be in the same order as the $firstArray. Notice the & to modify the actual value in the array:
foreach($firstArray as $key => &$value) {
$value['stockQT'] = $secondArray[$key];
}
Or alternately loop $secondArray and use the key to modify $firstArray:
foreach($secondArray as $key => $value) {
$firstArray[$key]['stockQT'] = $value;
}

Related

How to remove doubles element in foreach loop and keep date assigned to original?

What I am trying to get is to remove duplicate values in the Rest field, but I want to assign / keep its date in the original. element:
array (size=413)
0 =>
array (size=5)
'Date' =>
array (size=1)
0 => int 1588520980
'Rest' => 123abc
1 =>
array (size=5)
'Date' =>
array (size=1)
0 => int 1588520981
'Rest' => qwe123
2 =>
array (size=5)
'Date' =>
array (size=1)
0 => int 1588520983
'Rest' => qwe123
I try it but it doesn't work
public function find_repeats($arr)
{
foreach(array_column($arr, 'Rest') as $ckey=>$value) {
$keys = array_reverse(array_keys(array_column($arr, 'Rest'), $value));
foreach ($keys as $v) {
if ($ckey != $v && isset($arr[$v]))
{
$arr[$ckey]['Date'][] = $arr[$v]['Date'][0];
unset($arr[$v]);
}
}
}
return $arr;
}
This is what the table should look like after this operation
array (size=413)
0 =>
array (size=5)
'Date' =>
array (size=1)
0 => int 1588520980
'Rest' => 123abc
1 =>
array (size=5)
'Date' =>
array (size=1)
0 => int 1588520981
1 => int 1588520983
'Rest' => qwe123
Thanks for help! :)
Simple solution without all these stacked functions:
$newData = [];
foreach ($arr as $item) {
$rest = $item['Rest'];
if (!isset($newData[$rest])) {
$newData[$rest] = $item;
} else {
$newData[$rest]['Date'][] = $item['Date'][0];
}
}
// optionally apply array_values to get 0-indexed array:
$newData = array_values($newData);

PHP Apply multiple callback functions when using array_map, array_walk etc. functions

I have encountered an array of serialized values like below:
Array
(
[primary] => Array
(
[key_type_0_key_name] => a:1:{i:0;s:5:"27232";}
[key_type_1_key_name] => a:1:{i:0;s:5:"27231";}
[key_type_2_key_name] => a:1:{i:0;s:5:"27147";}
[key_type_3_key_name] => a:1:{i:0;s:5:"27157";}
)
[additional] => Array
(
[key_type_0_key_othername] => a:1:{i:0;s:5:"27169";}
[key_type_1_key_othername] => a:1:{i:0;s:5:"27160";}
[key_type_2_key_othername] => a:1:{i:0;s:5:"27103";}
[key_type_3_key_othername] => a:1:{i:0;s:5:"27149";}
)
)
Now I need to apply two functions namely, unserialize and array_shift in specified order to extract the scalar values like 27169 and store in another array, how can I do that in one pass of array_map or I have to run array_map two times compulsorily ?
Also one problem is with recursion, only array_walk_recursive handles recursion properly, but in my case if I try below code, I am getting the given error:
return array_walk_recursive($array, function ( &$value ) {
$value = array_shift( unserialize( $value ) );
});
Error:
Strict Standards: Only variables should be passed by reference in /path/to/file.php on line 367
Expected Result:
Array
(
[primary] => Array
(
27232
27231
27147
27157
)
[additional] => Array
(
27169
27160
27103
27149
)
)
With no calls to array_map.
<?php
$data = [
'primary' =>
[
'a:1:{i:0;s:5:"27232";}',
'a:1:{i:0;s:5:"27231";}',
'a:1:{i:0;s:5:"27147";}',
'a:1:{i:0;s:5:"27157";}'
],
'additional' =>
[
'a:1:{i:0;s:5:"27169";}',
'a:1:{i:0;s:5:"27160";}',
'a:1:{i:0;s:5:"27103";}',
'a:1:{i:0;s:5:"27149";}'
]
];
$numbers = [];
foreach($data as $key=>$value) {
foreach($value as $k=>$v) {
$unserialized = unserialize($v);
$numbers[$key][] = (int) array_shift($unserialized);
}
}
var_dump($numbers);
Output:
array (size=2)
'primary' =>
array (size=4)
0 => int 27232
1 => int 27231
2 => int 27147
3 => int 27157
'additional' =>
array (size=4)
0 => int 27169
1 => int 27160
2 => int 27103
3 => int 27149
Here a mutating array_walk example with three array_map calls. Far uglier and harder to read in my eyes, but each their own:
array_walk($data, function(&$v) {
$v = array_map('intval', array_map('array_shift', array_map('unserialize', $v)));
}
);
var_dump($data);
Output:
array (size=2)
'primary' =>
array (size=4)
0 => int 27232
1 => int 27231
2 => int 27147
3 => int 27157
'additional' =>
array (size=4)
0 => int 27169
1 => int 27160
2 => int 27103
3 => int 27149
Allow me to answer the question that was asked. Yes, yes you can... and you nearly had it!
You only needed to change the way that you were accessing the value. Replace the array_shift() call with [0] -- this eliminates the Strict Standards error.
Code: (Demo)
$array=[
'primary' =>
[
'a:1:{i:0;s:5:"27232";}',
'a:1:{i:0;s:5:"27231";}',
'a:1:{i:0;s:5:"27147";}',
'a:1:{i:0;s:5:"27157";}'
],
'additional' =>
[
'a:1:{i:0;s:5:"27169";}',
'a:1:{i:0;s:5:"27160";}',
'a:1:{i:0;s:5:"27103";}',
'a:1:{i:0;s:5:"27149";}'
]
];
array_walk_recursive($array,function(&$v){$v=unserialize($v)[0];});
var_export($array);
Output:
array (
'primary' =>
array (
0 => '27232',
1 => '27231',
2 => '27147',
3 => '27157',
),
'additional' =>
array (
0 => '27169',
1 => '27160',
2 => '27103',
3 => '27149',
),
)

Laravel 5 adding an element in an array does not work

I am getting an array from table questions
$questions = Category::where('slug', $slug)->first()->questions->toArray();
then using foreach I iterate over array and push an array element during each iteration like below
foreach ($questions as $question) {
$question['options'] = Option::where('question_id', $question['id'])->get()->toArray();
}
Ideally I should get response like below
array (size=5)
0 =>
array (size=6)
'id' => int 1
'category_id' => int 1
'questions' => string 'The ozone layer restricts' (length=25)
'answer_id' => int 4
'image_path' => string '' (length=0)
'options' =>
array (size=4)
0 =>
array (size=3)
...
1 =>
array (size=3)
...
2 =>
array (size=3)
...
3 =>
array (size=3)
...
1 =>
array (size=6)
'id' => int 2
'category_id' => int 1
'questions' => string 'Ecology deals with' (length=18)
'answer_id' => int 10
'image_path' => string '' (length=0)
'options' =>
array (size=4)
0 =>
array (size=3)
...
1 =>
array (size=3)
...
2 =>
array (size=3)
...
3 =>
array (size=3)
...
but Actually I am not getting options key into my questions array
The issue here is when you do a foreach, you are referring to the array by value - that is, under the hood PHP will create a copy of the variable inside the array. What you need is to access each element in the foreach by reference (note the & next to $q)
foreach ($questions as & $q) {
$q['options'] = Option::where('question_id', '=', $q['id'])->get()->toArray();
}
See:
Passing by references and the PHP docs on foreach.
Note: This is not really a Laravel issue, just PHP.
Try this (& in foreach):
foreach ($questions as & $question) {
$question['options'] = Option::where('question_id', $question['id'])->get()->toArray();
}
You can try:
foreach ($questions as $key=>$question) {
$questions[$key]['options'] = Option::where('question_id',$question['id'])->get()->toArray();
}

Merge multidimensional PHP arrays

From this foreach:
foreach ($statisticheProdotti as $values) {
$prod[] = $values['nome'];
$nomi = array_values(array_unique($prod, SORT_REGULAR));
$arr = array_combine(range(1, 12), range(1, 12));
foreach ($arr as $key => $val) {
$data = ($val == $values['mese']) ? $values['data'] : 0;
$arr[$val] = $data;
}
$prodotti[] = ['name' => $values['nome'], 'data' => array_values($arr)];
}
I get this array:
array (size=14)
0 =>
array (size=2)
'name' => string 'COMBIART PLUS' (length=13)
'data' =>
array (size=12)
0 => string '92' (length=2)
1 => int 0
2 => int 0
3 => int 0
4 => int 0
5 => int 0
6 => int 0
7 => int 0
8 => int 0
9 => int 0
10 => int 0
11 => int 0
1 =>
array (size=2)
'name' => string 'COMBIART PLUS' (length=13)
'data' =>
array (size=12)
0 => int 0
1 => int 0
2 => int 0
3 => int 0
4 => int 0
5 => int 0
6 => int 0
7 => int 0
8 => int 0
9 => int 0
10 => int 0
11 => string '92' (length=2)
2 =>
array (size=2)
'name' => string 'SECUR' (length=10)
'data' =>
array (size=12)
0 => string '5' (length=1)
1 => int 0
2 => int 0
3 => int 0
4 => int 0
5 => int 0
6 => int 0
7 => int 0
8 => int 0
9 => int 0
10 => int 0
11 => int 0
3 =>
.....`
I need to remove duplicated name and have unique array data.
Final output should be (example from index 0 and 1 which have same 'name'):
['name' => 'COMBIART PLUS', 'data' => [92, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 92]].
I hope I've well explained my problem.
Thanks
Sorry it's taken me a while to respond to this.
This might not be the most elegant way to do this, but assuming you want to combine the arrays with the same name, and combine the data array to make a unique array by using the values and the keys (assuming zero is not useful here), you can do something like this:
$output = array();
foreach ($example as $data) {
// Use the name as a quick array key reference to avoid having to search a second level of the array
$key = $data['name'];
if (!array_key_exists($key, $output)) {
// Instantiate the first entry using the name as the array key (we can reset this later)
$output[$key] = array(
'name' => $key,
'data' => $data['data']
);
// Skip the rest of this loop
continue;
}
// An entry already exists for the name, so merge any unique values into the array using the
// keys AND values to determine if something is unique. Zero is treated as empty.
foreach ($data['data'] as $newKey => $newValue) {
if (empty($output[$key]['data'][$newKey])) {
// Add a new unique entry to the output array (zero counts as empty here)
$output[$key]['data'][$newKey] = $newValue;
}
}
}
// Remove the name from the keys now
$output = array_values($output);
This should give you the result you're after. Example here.
thanks for your help scrowler, thanks to your code I have been able to get what I needed but I've just changed something to adapt it to my project...
function generateChartData($array) {
$prodArr = [];
$oldProd = '';
$arr = array_fill(0, 12, 0);
foreach ($array as $values) {
$Prod = $values['name'];
if ($Prod !== $oldProd) {
if (!empty($oldProd)) {
$prodotti[] = ['name' => $oldProd, 'data' => $arr];
}
$oldProd = $Prod;
}
foreach ($arr as $key => $val) {
if ($key == $values['mese'] - 1) {
$arr[$key] = (int) $values['data'];
}
}
}
// get last item
if (!empty($oldProd)) {
$prodArr[] = ['name' => $oldProd, 'data' => $arr];
}
return $prodArr;
}

How to map the two arrays with a duplicate value?

I have two arrays.
$array1 = ['id_e' =>[91707, 91708]];
$array2 = ['id_s' => [18, 57]];
If I want to insert or delete into the database, I want to make one-to-many mappings on these two arrays. And the result I expect it to be a new array as shown below.
Final Array:
array (size=4)
0 =>
array (size=2)
'id_e' => int 91707
'id_s' => int 18
1 =>
array (size=2)
'id_e' => int 91707
'id_s' => int 57
array (size=2)
2 =>
array (size=2)
'id_e' => int 91708
'id_s' => int 18
3 =>
array (size=2)
'id_e' => int 91708
'id_s' => int 57
I'm stuck after returning array1 and array2. I'm a beginner in php.
How do I do this?
Easiest way is:
$res = array();
foreach ($array1['id_e'] as $ide)
foreach ($array2['id_s'] as $ids)
$res[] = array('id_e' => $ide, 'id_s' => $ids);

Categories