How to select arrays in multidimensional array with a value in php - php

To put it right lets say I have an array stores-
array:3 [▼
0 => "store3"
1 => "store"
2 => "store2"
]
This is the array which holds values.
Other array products holds all the data:-
array:2 [▼
0 => array:2 [▼
"store" => "store"
"product" => "1"
]
1 => array:2 [▼
"store" => "store"
"product" => "4"
]
2 => array:2 [▼
"store" => "store2"
"product" => "2"
]
3 => array:2 [▼
"store" => "store2"
"product" => "3"
]
4 => array:2 [▼
"store" => "store3"
"product" => "7"
]
5 => array:2 [▼
"store" => "store3"
"product" => "11"
]
]
What I want is that a value is picked from stores array eg store3 then it is compared with products array and being searched and extract all the arrays inside products array which has the store value store3 and store it in another new array named store3
I have tried to do it but it was very wrong I mean it didn't work! I will post it if anyone say so but can anyone accomplish this?
My work:-
$temp = array();
for($i=0; $i<count($stores); $i++)
{
//$stores[$i] = array();
foreach($products as $p)
{
if(session($stores[$i]) == $p['store'])
{
if(count(session($stores[$i])) == 0)
{
$temp['product'] = $p['product'];
session($stores[$i])->push($temp['product']);
}
else if(!in_array($p['product'],$stores[$i]))
{
$temp['product'] = $p['product'];
session($stores[$i])->push($temp['product']);
}
}
}
}

Do it like below:-
$final_array = array();
foreach($array1 as $arr){
foreach($array2 as $arr2){
if($arr == $arr2['store']){
$final_array[$arr]['product'][] = $arr2['product'];
}
}
}
echo "<pre/>";print_r($final_array);
Output:-https://eval.in/752498

using array_walk
$array = [];
array_walk($products, function ($value, $key) use ($stores, &$array) {
$array[$value['store']][] = $value['product'];
});
live sample : https://3v4l.org/BfeMm

using array filter
$store = 'store1';
$products = array_filter($products, function($product) use($store) {
return (isset($product['store']) and $product['store'] == $store);
});
var_dump($products);
https://eval.in/752508

I made a simple function to find products in store
function searchProduct($products,$storeName){
$results =array();
foreach($products as $product){
if(in_array($storeName,array_values($product)))
$results[] = $product;
}
return $results;
}
print_r(searchProduct($products,'store3'));

Related

Is there an alternative for array_merge?

The problem is, I'm not getting the expected results of my array code.
I've tried doing the array_merge, but all it does was to merge all the arrays.
$medicine_order = $request['medicine_id'];
array:3 [▼
0 => "25"
1 => "32"
2 => "30"
]
$medicine_quantity = $request['medicine_quantity'];
array:3 [▼
0 => "3"
1 => "10"
2 => "6"
]
$count = 0;
foreach ($medicine_order as $id) {
$item = new Historyitem;
$item->medicine_id = $id;
foreach ($medicine_quantity as $id2) {
$item->historyitem_quantity = $id2;
}
$item->save();
$count++;
}
I wanted to store these values in my DB.
array:3 [▼
0 => "25"
1 => "3"
]
array:3 [▼
0 => "32"
1 => "10"
]
array:3 [▼
0 => "30"
1 => "6"
]
but instead I get these values:
array:3 [▼
0 => "25"
1 => "6"
]
array:3 [▼
0 => "32"
1 => "6"
]
array:3 [▼
0 => "30"
1 => "6"
]
Solution is change your foreach loop to this:
$count = 0;
foreach ($medicine_order as $key=>$id) {
$item = new Historyitem;
$item->medicine_id = $id;
$item->historyitem_quantity = $medicine_quantity[$key];
$item->save();
$count++;
}
Reason why you are getting wrong result is, your internal foreach loop, it iterates over every element of your $medicine_quantity array and every time it replaces the older value with new value, hence you are getting the value of last index i.e., "6" in final result.
You need to process the $medicine_quantity values in the same order as the $medicine_order values, which you can do by matching the keys to each array. Try this instead:
foreach ($medicine_order as $key => $id) {
$item = new Historyitem;
$item->medicine_id = $id;
$item->historyitem_quantity = $medicine_quantity[$key];
$item->save();
$count++;
}

Looping a Multi Dimensional Array

I encountered this kind of array in my tasks. It's a multi dimensional array.
In the form, I have this,
particular[particular][]
particular[percentage][]
particular[remarks][]
So what I'm doing is, I'm getting request
$inputs = $request->all();
this returns
array:3 [▼
"particular" => array:3 [▶]
"percentage" => array:3 [▶]
"remarks" => array:3 [▶]
]
inside, each of them have
array:3 [▼
"particular" => array:3 [▼
0 => "11"
1 => "22"
2 => "33"
]
"percentage" => array:3 [▼
0 => "11"
1 => "22"
2 => "33"
]
"remarks" => array:3 [▼
0 => "na1"
1 => "na2"
2 => "na3"
]
]
I tried looping it
foreach ($inputs as $input) {
dd($input);
}
but I only get the first one "particular" => array:3 [▶]
What I'm after is, I need to save those value in database
$particular = new Particular;
$particular->particular = particular;
$particular->percentage = percentage;
$particular->remarks = remarks;
$particular->save();
dd means "dump and DIE" so your script dies on first iteration.
You can:
$particular = new Particular;
$particular->particular = $inputs['particular'];
$particular->percentage = $inputs['percentage'];
$particular->remarks = $inputs['remarks'];
$particular->save();
Also, if you need to just dump something - there's a dump function (surprise!):
foreach ($inputs as $input) {
dump($input);
}
I managed to find a solution. I don't know if this is the proper, but for now atleast it work for me.
$array1 = $request->particular;
$array2 = $request->percentage;
$array3 = $request->remarks;
$merge = [$array1, $array2, $array3];
foreach ($merge[0] as $key => $value) {
$particular = new Particular;
$particular->particular = $merge[0][$key];
foreach ($merge[1] as $x => $y) {
$particular->percentage = $merge[1][$key];
}
foreach ($merge[2] as $i => $d) {
$particular->remarks = $merge[2][$key];
}
$particular->report_id = $report->id;
$particular->save();
}

Convert three dimensional array to two dimensional array in PHP [duplicate]

This question already has answers here:
How to Flatten a Multidimensional Array?
(31 answers)
Closed 6 years ago.
A little help needed here
I have this array:
0 => array:4 [▼
"StudentName" => "John Doe "
"StudentNumber" => "2055222"
0 => array:1 [▼
"Test" => 33.5
]
1 => array:1 [▼
"Assignment" => 57.0
]
]
1 => array:4 [▼
"StudentName" => "Jane Doe"
"StudentNumber" => "5222112"
0 => array:1 [▼
"Test" => 47.0
]
1 => array:1 [▼
"Assignment" => 68.0
]
]
2 => array:4 [▼
"StudentName" => "Alice Doe"
"StudentNumber" => "5555555"
0 => array:1 [▼
"Test" => 0.0
]
1 => array:1 [▼
"Assignment" => 67.0
]
]
And I want to convert it to look like this:
0 => array:4 [▼
"StudentName" => "John Doe "
"StudentNumber" => "20160022"
"Test" => 33.5
"Assignment" => 57.0]
Is there some sort of php function I can use?
Edit: Added more examples to help you think of a better solution
There's no native array flatten in PHP but you can do this:
function array_flatten($array) {
if (!is_array($array)) {
return false;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
} else {
$result[$key] = $value;
}
}
return $result;
}
Found here
Also numerous other approaches here: How to Flatten a Multidimensional Array?
You can do it using like this (not tested):
$arr = Array();
foreach($oldArr AS $k => $v){
if(is_array($v)){
foreach($v AS $a => $b){
$arr[$a] = $b;
}
}else{
$arr[$k] = $v;
}
}
This should work:
// Store your new array in a separate variable to avoid key conflicts with trying to us unset() in a loop
$new_array = array();
foreach($original_array as $k=>$v)
{
if(is_array($v)) // check if element is an array
{
foreach($v as $k2=>$v2) // loop the sub-array and add its keys/indexes to the new array
{
$new_array[$k2] = $v2;
}
}
else
{
// the element is not a sub-array so just add the key and value to the new array
$new_array[$k] = $v;
}
}

I want to split an array of arrays into coresponding arrays using in laravel 5.2

I have an array of arrays carrying data of multiple forms
i wanna split each form's data into a single array so i can store it to DB
currently doing
public function storeWBS(Request $request)
{
$value = $request->all();
$formValue = new WorkBreakdownStructure;
$count = 0;
$data_array1 = array();
foreach ($value as $key => $val2) {
$data_array= $val2;
if (is_array($val2)) {
array_push($data_array1, $val2);
}
}
dd($value);
exit;
$data_array1->save();
}
and Getting this result
array:4 [▼
"_token" => "bcK0e9z168ib7rbSZpoRPLWbhx3bRIHq1NqzfNeX"
"idea_id" => array:3 [▼
0 => "1"
1 => "1"
2 => "1"
]
"wbs_description" => array:3 [▼
0 => "Visit Campus to read about making great videos and more"
1 => "Visit Campus to read about \r\n"
2 => "Visit Campus to read about making great"
]
"percentage" => array:3 [▼
0 => "30"
1 => "30"
2 => "40"
]
]
i want the to get all values of inner array's index 0 to be in one array
i.e,
"idea_id"
=> "1"
"wbs_description"
=> "Visit Campus to read about making great videos and more"
"percentage"
=> "30"
from above i tried to run an inner loop but it'll result with same 3 arrays
foreach ($arr as $key => $val2) {
$data_array= $val2;
if (is_array($val2)) {
$count = 0;
foreach ($val2 as $k=>$v) {
$data_array1[$count][$key] = $v;
$count++;
}
}
}

Search array of objects for multidimensional array values in PHP

I have following task to do, if there is any chance I would appreciate some help to make it in as efficient way as possible. I need to compare values from array of objects (which comes from Laravel Query Builder join query) with array values.
Objects consist of database stored values:
0 => array:2 [
0 => {#912
+"addition_id": 1
+"valid_from": "2015-09-13 00:00:00"
+"valid_to": "2015-09-19 00:00:00"
+"price": "0.00"
+"mode": 0
+"alias": "Breakfast"
}
1 => {#911
+"addition_id": 2
+"valid_from": "2015-09-13 00:00:00"
+"valid_to": "2015-09-19 00:00:00"
+"price": "10.00"
+"mode": 1
+"alias": "Dinner"
}
while array includes new data, being processed by my method.
0 => array:3 [
0 => array:6 [
"id" => 1
"alias" => "Breakfast"
"price" => "0.00"
"mode" => 0
"created_at" => "2015-09-12 21:25:03"
"updated_at" => "2015-09-12 21:25:03"
]
1 => array:6 [
"id" => 2
"alias" => "Dinner"
"price" => "10.00"
"mode" => 1
"created_at" => "2015-09-12 21:25:18"
"updated_at" => "2015-09-12 21:25:18"
]
2 => array:6 [
"id" => 3
"alias" => "Sauna Access"
"price" => "50.00"
"mode" => 0
"created_at" => "2015-09-12 21:25:35"
"updated_at" => "2015-09-12 21:25:35"
]
]
Now, what I need to do is to find out what position of the array was not in the object (compare id with addition_id) and return it.
Is there any way to do it without two nested foreach loops? I think it can be done somehow smart with array_filter, but I'm not really sure how to write efficient callback (beginner here).
The only way I could get around this was:
private function compareAdditions(array $old,array $new)
{
$difference = $new;
foreach($new as $key => $value) {
foreach($old as $oldEntry) {
if($oldEntry->addition_id == $value['id']) {
unset($difference[$key]);
}
}
}
return $difference;
}
But I would really like to make it without two foreach loops. Help will be very appreciated :)
This might be overkill but it uses a function i write in every project, precisely for these kind of situations :
function additionals($original, $additions) {
$nonExisiting = [];
//convert all the objects in arrays
$additions = json_decode(json_encode($additions), true);
//create an index
$index = hashtable2list($original, 'id');
for(reset($additions); current($additions); next($additions)) {
$pos = array_search(current($additions)['addition_id'], $index);
if($pos !== false) {
//We could replace the originals with the additions in the same loop and save resources
//$original[$pos] = current($additions);
} else {
$nonExisiting[] = current($additions);
}
}
return $nonExisiting;
}
function hashtable2list( $hashtable, $key ){
$array = [];
foreach($hashtable as $entry) {
if( is_array($entry) && isset($entry[$key])) {
$array[] = $entry[$key];
} elseif( is_object($entry) && isset($entry->$key) ) {
$array[] = $entry->$key;
} else {
$array[] = null;
}
}
return $array;
}

Categories