I have a multi dimensional array with some values coming from a foreach, i need to insert this values into the array, but at this moment my result is this, not sure why:
Array
(
[0] => Array
(
[title] => MySecure
)
[1] => Array
(
[productTitle] => My New Product
)
[2] => Array
(
[title] => My Second Company
)
[3] => Array
(
[productTitle] => Another Product
)
[4] => Array
(
[productTitle] => Away Product
)
)
This is wrong, what i need is:
Array
(
[0] => Array
(
[title] => MySecure
[productTitle] => My New Product
)
[2] => Array
(
[title] => My Second Company
[productTitle] => Another Product
[productTitle] => Away Product
)
)
So this is what i have done:
$companies[] = [
'title' => $getCompanie->getTitle()
];
Then inside products :
$companies[] = [
'productTitle' => $getProduct->getTitle(),
];
so i assume im using the wrong array call, not sure about array_push?
You need to add both keys in the same inner array, rather than pushing them separately.
Use nested loops to get all the products associated with a company in the same loop.
$companies = [];
foreach ($all_companies as $companie) {
$products = [];
foreach ($companie->getProducts() as $getProduct) {
$products[] = $getProduct->getTitle());
}
$companies[] = [
'title' => $companie->getTitle(),
'productTitle' => $products
]
}
I've had to make up names for some of the things I assumed are in your code. You should be able to extrapolate from this to your actual design.
$newArray= [
'title' => array_map($yourArray,fn($ar)=>$ar['title']),
'productTitle' => array_map($yourArray,fn($ar)=>$ar['productTitle'])
];
Related
How to move array in multidimensional aray with key value?
I'm using array_push to add values to a multidimensional array. i have an array
$myArray = Array(Array('code' => '1','room' => Array('name' => 'Room-A')),Array('code' =>'1','room' => Array('name' => 'Room-B'
)), Array('code' => '2','room' => Array('name' => 'Vip-1')),Array('code' => '2','room' => Array('name' => 'Vip-2')));
i tried using code like this:
for ($i=0; $i <count($myArray) ; $i++) {
if ($myArray[$i]['code']=='1') {
array_push($myArray[$i]['room'], $myArray[$i]['room']);
}
else{
array_push($myArray[$i]['room'], $myArray[$i]['room']);
}
}
i want the result like this :
Array
(
[0] => Array
(
[code] => 1
[room] => Array
(
[0] => Array
(
[name] => Room-A
)
[1] => Array
(
[name] => Room-B
)
)
)
[1] => Array
(
[code] => 2
[room] => Array
(
[0] => Array
(
[name] => Vip-1
)
[1] => Array
(
[name] => Vip-2
)
)
)
)
Any idea how to join this array?
You can use array_reduce to summarize the array into an associative array using the code as the key. Use array_values to convert the associative array into a simple array.
$myArray = ....
$result = array_values(array_reduce($myArray, function($c, $v){
if ( !isset( $c[ $v['code'] ] ) ) $c[ $v['code'] ] = array( 'code' => $v['code'], 'room' => array() );
$c[ $v['code'] ]['room'][] = $v['room'];
return $c;
},array()));
echo "<pre>";
print_r( $result );
echo "</pre>";
This will result to:
Array
(
[0] => Array
(
[code] => 1
[room] => Array
(
[0] => Array
(
[name] => Room-A
)
[1] => Array
(
[name] => Room-B
)
)
)
[1] => Array
(
[code] => 2
[room] => Array
(
[0] => Array
(
[name] => Vip-1
)
[1] => Array
(
[name] => Vip-2
)
)
)
)
This is the foreach() equivalent of Eddie's answer (I find it easier to read/maintain).
Code: (Demo)
$myArray = [
['code' => '1', 'room' => ['name' => 'Room-A']],
['code' => '1', 'room' => ['name' => 'Room-B']],
['code' => '2', 'room' => ['name' => 'Vip-1']],
['code' => '2', 'room' => ['name' => 'Vip-2']]
];
foreach ($myArray as $row) {
if (!isset($result[$row['code']])) {
$result[$row['code']] = ['code' => $row['code'], 'room' => [$row['room']]];
// ^------------^-- pushed deeper
} else {
$result[$row['code']]['room'][] = $row['room'];
// ^^-- pushed deeper
}
}
var_export(array_values($result));
This question is very similar to many pre-existing questions that want to group by a particular column. I was not able to find an exact duplicate to close with because the requirement of this question is to created a deeper structure to contain the room sub arrays.
Typically I would write:
if (!isset($result[$row['code']])) {
$result[$row['code']] = $row;
to cut down on syntax, but the new output structure must be applied to both the if and the else.
To avoid key duplication/collision, the room subarrays need to be pushed/indexed to a lower level.
In the end, the technique has been demonstrated here many, many times on StackOverflow. You target an element value to group by and use that value as the temporary key as you iterate the input array. Checking if the temporary keys exist or not is the fastest way to determine if a group is new or previously encountered. When you are done, call array_values() to remove the temporary keys (re-index the array).
I try to create a new array from an complex array.
If there's no easy solution, every hint would help to search more successful.
I have this complex array (shortened a lot) and want to build a new 2 dimensional array:
array (
[key1] => value1
[key2] => value2
[category] => array (
[key3] => value3
[key4] => array (
[small] => value6
[large] => value7
)
[items] => array (
[0] => array (
[aTag] => #PU2RRL
[name] => 3PL
[position] => 25
[versions] => array (
[0] => array (
[bTag] => #KF67RL
[color] => blue
[id] => 001
)
[1] => array (
[bTag] => #Z8TR4
[color] => red
[id] => 002
)
)
)
[1] => array (
...
This is the array I want to create:
array(
[001] => array (
[aTag] => #PU2RRL
[name] => 3PL
[position] => 25
[bTag] => #KF67RL
[color] => blue
)
[002] => array (
[aTag] => #PU2RRL
[name] => 3PL
[position] => 25
[bTag] => #Z8TR4
[color] => blue))
With ID as key and this values:
$itemAll = array(
$array[category][items][0][versions][0][id] => array(
"aTag" => $array[category][items][0][aTag],
"name" => $array[category][items][0][name],
"position" => $array[category][items][0][position],
"bTag" => $array[category][items][0][versions][0][bTag],
"color" => $array[category][items][0][versions][0][color],
)
);
I have no clue how to create this array with foreach loops for "items" and versions with the ID as primary key, any hints?
EDIT: huge thanks to #DeeDuu! Because I had multiple items I added another foreach:
$new_array = array();
// i have multiple items, so I removed [0]:
$items = $array["category"]["items"];
// added another foreach
foreach ($items as $item) {
// changed $items to $item
$shared_properties = array(
"aTag" => $item["aTag"],
"name" => $item["name"],
"position" => $item["position"]
);
// changed $items to $item
foreach ($item["versions"] as $version) {
$specific_properties = array(
"bTag" => $version["bTag"],
"color" => $version["color"]
);
$new_entry = array_merge(
$shared_properties,
$specific_properties
);
$new_array[$version["id"]] = $new_entry; }}
If I understand correctly what you want, something like the following should work.
// This is the target array where we will save the recombinated data
$new_array = array();
// Store the relevant subarray in a new variable;
// This makes the subsequent code shorter
$items = $array["category"]["items"][0];
// This gives the data that will be common to all the new entries,
// for all versions seem to share aTag, name and position
$shared_properties = array(
"aTag" => $items["aTag"],
"name" => $items["name"],
"position" => $items["position"]
);
// Alright, let's loop over the versions
foreach ($items["versions"] as $version) {
// Another array for the data that is specific
// to the version we're currently looking at
$specific_properties = array(
"bTag" => $version["bTag"],
"color" => $version["color"]
);
// The new entry is a combination of the shared and the
// specific properties; array_merge will do that for us
$new_entry = array_merge(
$shared_properties,
$specific_properties
);
// Now add to the new array
$new_array[$version["id"]] = $new_entry;
}
I need to dynamically produce child elements of an array, these are arrays them selves. So the end result should be (this is a simplified version of the code below to make it easier to understand):
Array
(
[id] => 5000038642
[name] => TrackVia Legacy Section of Array
[description] =>
[table_id] => 5000005024
[records] => Array
(
[0] => Array
(
[id] => 1
[table_id] => 1
[fields] => Array
(
[Name] => First Item
)
)
[1] => Array
(
[id] => 1
[table_id] => 1
[fields] => Array
(
[Name] => Second Item
)
)
)
)
The nested arrays within Results are produced dynamically from a MySQL table, so >
$allItems = array();
$item = array();
// Get each result and build the arrya
while($row = $resultAvailableBoxes->fetch_assoc()) {
$item = array (
"id"=> $row['id'],
"table_id"=> $row['id'],
"fields"=> array (
"Name"=> $row['box_title'],
)
);
// Append the arrays on to each other
$allItems[] = array_merge($allItems, $item);
}
// Place the arrays within the "parent" array
$completeArray = array(
"id"=> 1000,
"name"=> "Sample",
"description"=> "",
"table_id"=> 1000,
"records"=>
$allItems
);
As you can see I am then also trying to append each new array on to the last, before placing those arrays in to the "parent" array. This is where the problems happen.
Using the method
$allItems[] = array_merge($allItems, $item);
I get every array appended on to the last, but then again and again. Like this:
Array
(
[id] => 5000038642
[name] => TrackVia Legacy Section of Array
[description] =>
[table_id] => 5000005024
[records] => Array
(
[0] => Array
(
[id] => 1
[table_id] => 1
[fields] => Array
(
[Name] => Texan BBQ 1
)
)
[1] => Array
(
[0] => Array
(
[id] => 1
[table_id] => 1
[fields] => Array
(
[Name] => Texan BBQ 1
)
)
[id] => 9
[table_id] => 9
[fields] => Array
(
[Name] => Goan Sorpotel with Pea & Mint Pilau and Tomato Chutney
)
)
)
)
When I have 20 items, you can see this would become massive list and just doesn't work. Using the method
$allItems = array_merge($allItems, $item);
Returns only the last array being appended (i.e. it always overwrites whats already in the "allItems" array.
I have also used a simple method that I didn't expect to work, and sure enough it didnt:
$allItems .= $item;
I've come to the conclusion after reading these stackover flow questions which seem like the same thing but aren't or give weird results that I must be approaching this all wrong. Is this the wrong method full stop, or is it that I have missed something out to stop the child elements being continually added?
Appending Arrays (Stack Overflow)
Can't concatenate 2 arrays in PHP
I've lost count of the other questions I've look at on this, including the PHP manual but I can't find anything more relevant the arrays_merge
why don't you just do this?
$items = array();
while($row = $resultAvailableBoxes->fetch_assoc()) {
$items[] = array (
"id"=> $row['id'],
"table_id"=> $row['id'],
"fields"=> array (
"Name"=> $row['box_title'],
)
);
}
// Place the arrays within the "parent" array
$completeArray = array(
"id"=> 1000,
"name"=> "Sample",
"description"=> "",
"table_id"=> 1000,
"records"=> $items
);
this should create an array with all the items and then add it to the $completeArray
Try to use $allItems[] = $item; instead of $allItems[] = array_merge($allItems, $item);
I have a multidimensional array that is displayed to users in a table, where they can select items by a checkbox.
When they've checked their items and submit, I've now got an array of id values that correspond to the myid key of the original sub arrays.
How can I search the original array and create a new array of only the matching selected items?
Array (
[0] => Array (
[myid] => 22
[Price] => Some price
[Title] => Some text
)
[1] => Array (
[myid] => 36
[Price] => Some price
[Title] => Some text
)
)
Any help would be greatly appreciated!
Simple way but can be optimized
<?php
$submittedVaule = array('12','14');
$subArray = array(0 => array('myid' => 12,'price' => '100','title' => 'test1'),1 => array('myid' => 13,'price' => '100','title' => 'test2'),2 => array('myid' => 14,'price' => '100','title' => 'test3'));
$finalarray = array();
foreach($subArray as $key=>$value){
if(in_array($value['myid'], $submittedVaule )) {
$finalarray[]=$subArray[$key];
}
}
print_r($finalarray);
?>
From the database I get the data in the following style:
Array
(
[0] => stdClass Object
(
[id] => 2
[name] => edit_sites
)
[1] => stdClass Object
(
[id] => 1
[name] => view_sites
)
)
Does Laravel have any built-in methods for obtaining data by the keys like this:
Array
(
[id] => Array
(
[0] => 1
[1] => 2
)
[name] => Array
(
[0] => view_sites
[1] => edit_sites
)
)
or i need to do it by myself ?
Unfortunately, there is none, you have to do it by yourself albeit an easy one really.
$processedData = array();
foreach($dbData as $row) {
foreach($row as $dbKey => $value) {
$processedData[$dbKey][] = $value;
}
}
If you're getting the data back as a raw array (which you seem to be), then array_pluck will do most of what you want:
For example:
// you could use this wherever you needed the specific lists
$ids = array_pluck($results, 'id'); // [ 1, 2 ]
// or if you wanted the array exactly as asked for in the question:
$sortedArray = array(
'id' => array_pluck($results, 'id'),
'name' => array_pluck($results, 'name')
);
// [
// 'id' => [1,2],
// 'name' => [ 'view_sites', 'edit_sites' ]
// ]
If you are getting the results as some kind of Illuminate\Support\Collection class (say, from an Eloquent query), then you can use the lists method on the Collection as an alias to array_pluck
$results->lists('id'); // [ 1, 2 ]