PHP array_merge overwrites itself - php

I'm struggling with array_merge to make an array of items. The code which I have:
$items = [];
foreach ($products as $product) {
Log::info($product->orderproduct->idorder_product);
$items = array_merge($items, [
'id' => $product->orderproduct->idorder_product
]);
}
Log::info(print_r($items, true));
The output is:
6
7
['id' => 7]
How can I create an array with both id's?

Not sure what result you expect, so there are 2 options:
foreach ($products as $product) {
Log::info($product->orderproduct->idorder_product);
// First
$items[] = $product->orderproduct->idorder_product;
// Second
$items[] = ['id' => $product->orderproduct->idorder_product];
}

Array merge is just another array which add into the bottom of the array.
I think you are misleading us on the result you want to get.
$items = array(); / $items = [];
you can push the data into array easily by this code
$items[] = array(
'id' => $product->orderproduct->idorder_product,
)

Related

PHP Array Iteration to Flatten All Possible Results

I don't know the term of what I am trying to do, so I can't seem to find a similar answer.
I'm trying to make an array that looks like the following:
array (
'birds' => array(
'parakeet',
'conure',
'woodpecker'),
'color' => array(
'red',
'blue',
'green'
),
'size' => array(
'large',
'medium',
'small'
));
to iterate through all possible permutations to look like the following
array(
array('parakeet','red','large'),
array('parakeet','red','medium'),
array('parakeet','red','small'),
array('parakeet','blue','large'),
array('parakeet','blue','medium'),
array('parakeet','blue','small'),
array('parakeet','green','large'),
array('parakeet','green','medium'),
array('parakeet','green','small'),
array('conure','red','large'),
..... etc
);
Any help would be very much appreciated! Thank you in advance!
Just create a step down loop on each level for bird, color and size. Then create a temporary container and continually merge it:
$data = [[]]; // initialize empty container
foreach ($arr as $key => $values) {
$tmp = []; // store it in here
foreach ($data as $d) {
foreach ($values as $value) {
$tmp[] = array_merge($d, [$value]); // then continually merge
}
}
$data = $tmp;
}
Just loop through what you need to, and build a new array as you go:
$newarray = $temparray = array();
foreach ( $oldarray['birds'] as $bird )
{
$temparray[] = $bird;
foreach ( $oldarray['color'] as $color )
{
$temparray[] = $color;
foreach ( $oldarray['size'] as $size )
{
$temparray[] = $size;
}
$newarray[] = $temparray;
unset ($temparray);
}
}

How can I remove all data in an array - PHP

I'm trying to delete all the data in this array. I'm beginer
$data = array(
['id' => 1, 'name' => 'Alex'],
['id' => 2, 'name' => 'Max'],
['id' => 3, 'name' => 'George']
);
I'm using this code to do it, but it doesn't work :(
foreach ($data as $item) {
unset($item);
}
When you want to clear the complete array, why not using unset($data)?
Your code does not work they way as you expect it, because in your loop you are defining a new variable $item. You are then unsetting this variable $item which has no effect on original the values of your $data array.
If you want to use a loop you need to define it like that:
foreach ($data as $index => $item) {
unset($data[$index]);
}
This clears all values from $data but not unsetting the $data array itself.
A more efficient way compared to the loop would be to just assign a empty array to $data like:
$data = [];

Creating Associative array (hardcoded key) from foreach in PHP

I have an array called $arr containing some information about users. Using $arr I want to create a new associative array with specific keys. That's what I got so far:
$groups = [];
foreach($arr as $val) {
$groups['first_key_name'] = $val->ID;
$groups['second_key_name'] = $val->login;
}
What I'm trying to achieve is a new array that has the following format:
'first_key_name' => $val->ID
'second_key_name' => $val->login
'first_key_name' => $val->ID
'second_key_name' => $val->login
The problem with my current approach is when I var_dump($groups) I only get one key with an empty value although the array should contain at least 10 entries.
The output of var_dump($groups):
array:1 [▼
"first_key_name" => "4"
]
What am I doing wrong?
You are overwriting your variables each time round the loop in this code
$groups = [];
foreach($arr as $val) {
$groups['first_key_name'] = $val->ID;
$groups['second_key_name'] = $val->login;
}
So instead do
$groups = [];
foreach($arr as $val) {
$groups[] = [
'first_key_name' => $val->ID
'second_key_name' => $val->login
];
}
This will create something like this
[0]
[
'first_key_name' = 1,
'second_key_name' = 99
]
[1]
[
'first_key_name' = 2,
'second_key_name' = 199
]
etc
You approach is overwriting the key value every time. That's why you need to use 2d array.
You can try like this:
$groups = [];
foreach($arr as $val) {
$groups[] = ['first_key_name' => $val->ID, 'second_key_name' => $val->login];
}
What happens here, is you are overwriting first_key_name and second_key_name in each turn of the loop. But you want to get an array with the new key=>value pairs.
To achieve that you have to append a new item to your array called $groups, like this:
$groups = [];
foreach ($arr as $val) {
$groups[] = [
'first_key_name' => $val->ID,
'second_key_name' => $val->login
];
}
You may also use array_map for this:
$groups = array_map(function ($val) {
return [
'first_key_name' => $val->ID,
'second_key_name' => $val->login,
];
}, $arr);

Loop through all the children item from an array to create JsTree Children Item

I'm having an issue with formatting JSON data for the jQuery JsTree. I've many children item that I'd like to show under the Root folder. However, when I can't figure out how to loop through all children item. The following code only prints 1 item from the children array. I'd like to print all the children item.
$children = [];
foreach ($items as $item) {
$children['id'] = $item['id'];
$children['text'] = $item['title'];
}
$data = [
'id' => 1,
'text' => 'Root',
'children' => $children
];
echo json_encode($data);
The above code print the following result:
{
"id":1,
"text":"Root",
"children":{
"id":"0B_J9f9IAYIKQczFkUERDUHpBYmc",
"text":"Complete Thesis.doc"
}
}
I've figured it out myself by assigning the empty array using the array key. Here's how I did it:
<?php
$children = [];
foreach ($items as $item => $value) {
$children[$item]['id'] = $value['id'];
$children[$item]['text'] = $value['title'];
}
$data = ['id' => 1, 'text' => 'Root',
'children' => $children
];
echo json_encode($data);
The above code returns the following result as the formatted JSON string for the JsTree:
{"id":1,"text":"Root","children":[{"id":"0B_J9f9IAYIKQemNzVzBhNDg2elE","text":"New Folder"},{"id":"0B_J9f9IAYIKQdkktWEREaHVLMUk","text":"New Folder"},{"id":"0B_J9f9IAYIKQX3pjUU5FTDBkUlE","text":"Erin VZBakker 4 thisis.pdf"},{"id":"0B_J9f9IAYIKQczFkUERDUHpBYmc","text":"Complete Thesis.doc"}]}

PHP Foreach array in array

I need make array in array. Like this:
$array = array(
array("value" => 1),
array("value2" => 2));
I've tried to code it:
foreach($labels as $stats => $label)
{
$array = array(
array($label, $registrations[$stats])
);
}
But it prints only one array, how to fix it? I know my code is bad, but I'm newbie in PHP :( Or I must use while?
On each iteration you should add new array to a result array:
$array = array();
foreach($labels as $stats => $label)
{
$array[] = array($label, $registrations[$stats]);
}
Or if you want key-value array:
$array = array();
foreach($labels as $stats => $label)
{
$array[$label] = $registrations[$stats];
}

Categories