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;
}
}
Related
Am working on some set of PHP array. Am trying to loop through each of them and check
the array whose name is equal to Josw Acade. Am using a for loop but I get zero
after extracting the data. I want to store the data in an array.
Array
array:6 [
0 => array:4 [
"id" => 1
"name" => "Josw Acade"
"value" => "Unlimited"
"plan_type" => "Superior"
]
1 => array:4 [
"id" => 2
"name" => "Verbal"
"value" => "true"
"plan_type" => "Superior"
]
2 => array:4 [
"id" => 12
"name" => "Josw Acade"
"value" => "$1,500,00"
"plan_type" => "Classic"
]
3 => array:4 [
"id" => 13
"name" => "Leon"
"value" => "true"
"plan_type" => "Classic"
]
4 => array:4 [
"id" => 14
"name" => "One Time"
"value" => "true"
"plan_type" => "Classic"
]
5 => array:4 [
"id" => 15
"name" => "Deat"
"value" => "$25,000"
"plan_type" => "Classic"
]
6 => array:4 [
"id" => 23
"name" => "Josw Acade"
"value" => "$100,000"
"plan_type" => "Essential"
]
]
Logic
$Inst = [];
for($med = 0; $med < count($array); $med++){
if($med['name'] == "Josw Acade"){
$Inst = $med['value'];
}
}
dd($Inst);
Your variables is not corretly set in the for loop, you are setting $med = 0 and acessing $med as an array.
Use filter, that runs a condition on each element and returns the items that satisfy that condition.
array_filter($array, function ($item) {
return $item['name'] === 'Josw Acade';
});
In general you don't have to make old school arrays anymore, foreach does the same.
$results = [];
foreach($array as $item)
{
if ($item['name'] === 'Josw Acade') {
$results[] = $item['value'];
}
}
You can use array_filter with callback
$filtered = array_filter($array, function($v){ return $v['name'] == 'Josw Acade'})
print_r($filtered);
You are looping through array; so on each iteration to get values; you need to pass index value and you are missing that. You are using $med as index.
Here is code.
$Inst = [];
for($med = 0; $med < count($array); $med++){
if($array[$med]['name'] == "Josw Acade"){
$Inst[] = $array[$med]['value'];
}
}
there is many way to do this but according to me the best way to use array_filer()
array_filter($array, function ($item) {
return $item['name'] === 'Josw Acade';
});
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();
}
I have the following structure array:
array:6 [▼
"593a4331b25f428814000035" => array:8 [▶]
"593a4331b25f428814000036" => array:8 [▶]
"593a4331b25f428814000037" => array:8 [▶]
"593a4331b25f428814000038" => array:8 [▼
"_id" => MongoId {#238 ▶}
"object_id" => "593a4331b25f428814000034"
"parameter_id" => "59398f5ab25f424016000029"
"value" => "1"
"children" => []
"parent_id" => "593a4331b25f428814000037"
"type" => "2"
"prefix" => "object"
]
"593a4331b25f428814000039" => array:8 [▶]
"593a4331b25f42881400003a" => array:8 [▶]
]
As you can see 3-th element of array has parent 593a4331b25f428814000037, where identificator is element in the same array.
How to put this element 593a4331b25f428814000038 inside parent in children?
In result I need to get:
"593a4331b25f428814000037" => array:8 [▼
"_id" => MongoId {#238 ▶}
"object_id" => "593a4331b25f428814000034"
"parameter_id" => "59398f5ab25f424016000029"
"value" => "1"
"children" => [ 0 => array("_id" => MongoId {#238 ▶}
"object_id" => "593a4331b25f428814000034"
"parameter_id" => "59398f5ab25f424016000029"
"value" => "1"
"children" => []
"parent_id" => "593a4331b25f428814000037"
"type" => "2"
"prefix" => "object")]
"parent_id" => "593a4331b25f428814000037"
"type" => "2"
"prefix" => "object"
]
I tried this way:
public function recursion($data){
foreach ($data as $k => $value) {
if (is_array($value['children']) && count($value['children']) > 0) {
$list[$k] = $value;
$list[$k]["children"] = $this->getChildren($all, $value['children']);
} else {
$list[$k] = $value;
}
}
return $list;
}
private function getChildren($all, $childs)
{
$list = [];
foreach ($childs as $k => $child) {
if (is_array($all[$child]['children'])) {
$tmpArray = $all[$child];
$tmpArray['children'] = $this->getChildren($all, $all[$child]['children']);
} else {
$tmpArray = $all[$child];
}
$list[] = $tmpArray;
}
return $list;
}
But it works incorrect
You can use array_reduce like:
$array = array_reduce($myArray, function ($carry, $item) {
if (empty($item['parent_id'])) {
$carry[$item['object_id']] = $item;
} else {
$carry[$item['parent_id']]['children'][] = $item;
}
return $carry;
}, []);
var_dump($array);
In this example I supposed the parent_id is empty for those items which doesn't belong to a another item. You can change that with isset in case there is no parent_id key
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'));
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++;
}
}
}