Joining arrays to go in to a multidimensional array - php

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);

Related

Adding variable to upcomming array

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'])
];

Change index of multidimensional array PHP

I've tried some solutions from:
In PHP, how do you change the key of an array element?
php array from multidimensional array keys values
But its is not exacly what i need, i tried to mix some solutions but notting helped.
I have an array from my database:
Array (
[0] => Array (
[ID] => 1
[USER_ID] => 1
[DATA] => UNIQUE
[VALUE] => buuu )
[1] => Array (
[ID] => 2
[USER_ID] => 1
[DATA] => NICKNAME
[VALUE] => NoAd ) )
And i want to transform that database to:
Array (
[UNIQUE] => buuu
[NICKNAME] => NoAd
[any new [2]...[3]... from previous array
after that code:
foreach($playerdata as $segment){
foreach($segment as $key => $value ){
$newArray[$value] = $value;
}
}
my array looks like:
Array ( [UNIQUE] => UNIQUE
[buuu] => buuu
[NICKNAME] => NICKNAME
[NoAd] => NoAd )
i tried use 3x foreach but it ends in error all time i think i need to change some variables in my foreach but no idea how.
Now that I see the other answers it seems it's array_column you are looking for.
It returns an array column and the third parameter is what the key name should be.
$player_data = array(array(
"ID" => 1,
"USER_ID" => 1,
"DATA" => "UNIQUE",
"VALUE" => "buuu"
),
array(
"ID" => 1,
"USER_ID" => 1,
"DATA" => "NICKNAME",
"VALUE" => "NoAd"
));
$new = array_column($player_data, "VALUE", "DATA");
var_dump($new);
Output:
array(2) {
["UNIQUE"]=>
string(4) "buuu"
["NICKNAME"]=>
string(4) "NoAd"
}
https://3v4l.org/ZAkgZ
There is no need for loops to solve this.
lets assume $playerdata has the below values
Array (
[0] => Array (
[ID] => 1
[USER_ID] => 1
[DATA] => UNIQUE
[VALUE] => buuu )
[1] => Array (
[ID] => 2
[USER_ID] => 1
[DATA] => NICKNAME
[VALUE] => NoAd ) )
[2]----
[3]----
$newArray = [];
foreach($playerdata as $record) {
$newArray[$record['DATA']] = $record['DATA'];
$newArray[$record['VALUE']] = $record['VALUE'];
}
print_r($newArray);
You could try something like the following:
$newArray = array();
foreach($playerdata as $segment){
$newArray[$segment['DATA']] = $segment['VALUE'];
}
This code gets the DATA as key and VALUE as value from each part of the array and stores it in $newArray.

PHP reorder multidimensional array based on single dimensional array

multidimensional array
Array
(
[0] => Array
(
[ID] => 5068
[Item] => 2737
[Unit] => 15
)
[1] => Array
(
[ID] => 5067
[Item] => 2737
[Unit] => 13
)
)
single dimensional array
Array (
[0] => 11
[1] => 13
[2] => 15
)
Expected output:
Array
(
[0] => Array
(
[ID] => 5067
[Item] => 2737
[Unit] => 13
)
[1] => Array
(
[ID] => 5068
[Item] => 2737
[Unit] => 15
)
)
It not necessary that single dimensional array must be in ASC/DESC order. I want to reorder multidimensional array according to single dimensional array based on unit value. How can I achieve this?
Maybe something like this would work?
$multiDimArray = [
0 => [
'ID' => 5068,
'Item' => 2737,
'Unit' => 15
],
1 => [
'ID' => 5067,
'Item' => 2737,
'Unit' => 13
]
];
$singleDim = [
11,13,15
];
usort($multiDimArray,function($a,$b){
global $singleDim;
return ($singleDim[0] >= $a['Unit']) ? -1 :1;
});
print_r($multiDimArray);
there's something in back of my head that tells me I'm missing something. But feel free to give it a go.
Assuming that the values in the single array all map to a value in Unit, you could loop the single dimensional array and then loop the values in the multidimensional array.
In the inner loop use in_array to check if the value from the single dimensional array occurs in the multidimensional array. If it does, you could for example add it to a new array.
$result = [];
foreach ($singleDimension as $sm) {
foreach ($multiDimensional as $md) {
if (in_array($sm, $md)) {
$result[] = $md;
}
}
}
Demo

PHP: create 2 dimensional array from multidimensional array with value as key

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;
}

PHP array's, how to access keys and values

Trying to learn multidimensional arrays but seem to constantly struggle with accessing them. I still have not got grasps of how you access them using index, keys, values.
How do I get to the actual word "Title" and it's value?
Here I have one I was playing with.
$shop = array( array( "Title" => "rose",
"Price" => 1.25,
"Number" => 15
),
array( "Title" => "daisy",
"Price" => 0.75,
"Number" => 25,
),
array( "Title" => "orchid",
"Price" => 1.15,
"Number" => 7
)
);
Which prints a structure such as this:
Array
(
[0] => Array
(
[Title] => rose
[Price] => 1.25
[Number] => 15
)
[1] => Array
(
[Title] => daisy
[Price] => 0.75
[Number] => 25
)
[2] => Array
(
[Title] => orchid
[Price] => 1.15
[Number] => 7
)
)
echo $shop[0][0][0]; //I Expect "rose" but I get "Undefined offset: 0"
echo $shop['Price']; //I expect 1.25 but I get "Undefined index: Price"
foreach($shop as $key=>$value)
{
echo $key; //I expect the key values "Title/Price/Number" instead I get Index numbers 0 1 2
echo $value; //I expect all values of keys e.g. "rose",1.25,15/"daisy",0.75,25/"orchid",1.15,7 Instead I get Array to string conversion error
}
What I am trying to do, is take all the title and value from the shop array, and put it into a new array called $x = array(); and then take a car key/value from a different array and combine them together.
so the new array ends up looking like this:
Array
(
[0] => Array
(
[Title] => rose //from $shop array
[Car] => Mercedez //from $car array
)
[1] => Array
(
[Title] => daisy //from $shop array
[Car] => Ford //from $car array
)
[2] => Array
(
[Title] => orchid //from $shop array
[Car] => Bentley //from $car array
)
)
Also is there a way to access the actual name of the key "title" and not a index number?
You have an array of arrays, therefore you'll need two loops.
foreach ($shop as $item) {
foreach ($item as $key => $value) {
echo $key;
echo $value;
}
}
Try this -
$newarray = array();
foreach($shop as $key=>$value) {
$newarray[$key]['Title'] = $value['Title'];
$newarray[$key]['Number'] = $value['Number'];
}
echo "<pre>";print_r($newarray);
Here, $newarray will give you output like this.
Array
(
[0] => Array
(
[Title] => rose
[Number] => 15
)
[1] => Array
(
[Title] => daisy
[Number] => 25
)
[2] => Array
(
[Title] => orchid
[Number] => 7
)
)
You could access by $shop[0]['Title']
0 means the first item in array and this item is also an array, which contains string keys so 'title' as second level.
To iterate it use:
//Syntax array as key => value (value is in this case also an array)
foreach($shop as $iterator_level1 => $shop_set){
//so you can access the 2. level by string key.
echo $shop_set['title'];
}
Hope this is helpful.

Categories