PHP Foreach array in array - php

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

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

Multidimensional array - replace

I have an array, similar to the following:
$array = [
['file' => 1, 'status' => 'pending'],
['file' => 2, 'status' => 'pending'],
];
What I want to do is to replace the statuspart, where the file is 1
I'm not sure if i can do this in a simple array, or using an in-built array_ method
I have something liek the following so far:
$data = [];
foreach($array as $arr => $val) {
if ($val['file'] == 1) {
$data['status'] = 'updated';
}
}
You're close, but as $data is array of arrays, you need to provide $arr as top-level key and even get rid of second array:
foreach($array as $arr => $val) {
if ($val['file'] == 1) {
$array[$arr]['status'] = 'updated';
}
}
This should give you an idea of how to tackle that.
if ($array[0]['file'] == 1) {
$array[0]['whatever'] = $array[0]['status'];
unset($array[0]['status']);
}
The 0 can ofcourse be changed by i in a loop if you wish to cycle through the entire array.

PHP array_merge overwrites itself

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

Loop over one array as if it was a multidimensional array

I have an array like:
$array = array(
'name' => 'Humphrey',
'email' => 'humphrey#wilkins.com
);
This is retrieved through a function that gets from the database. If there is more than one result retrieved, it looks like:
$array = array(
[0] => array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
[1] => array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
If the second is returned, I can do a simple foreach($array as $key => $person), but if there is only one result returned (the first example), I can't run a foreach on this as I need to access like: $person['name'] within the foreach loop.
Is there any way to make the one result believe its a multidimensional array?
Try this :
if(!is_array($array[0])) {
$new_array[] = $array;
$array = $new_array;
}
I would highly recommended making your data's structure the same regardless of how many elements are returned. It will help log terms and this will have to be done anywhere that function is called which seems like a waste.
You can check if a key exists and do some logic based on that condition.
if(array_key_exists("name", $array){
//There is one result
$array['name']; //...
} else {
//More then one
foreach($array as $k => $v){
//Do logic
}
}
You will have the keys in the first instance in the second yours keys would be the index.
Based on this, try:
function isAssoc(array $arr)
{
if (array() === $arr) return false;
return array_keys($arr) !== range(0, count($arr) - 1);
}
if(isAssoc($array)){
$array[] = $array;
}
First check if the array key 'name' exists in the given array.
If it does, then it isn't a multi-dimensional array.
Here's how you can make it multi-dimensional:
if(array_key_exists("name",$array))
{
$array = array($array);
}
Now you can loop through the array assuming it's a multidimensional array.
foreach($array as $key => $person)
{
$name = $person['name'];
echo $name;
}
The reason of this is probably because you use either fetch() or fetchAll() on your db. Anyway there are solutions that uses some tricks like:
$arr = !is_array($arr[0]) ? $arr : $arr[0];
or
is_array($arr[0]) && ($arr = $arr[0]);
but there is other option with array_walk_recursive()
$array = array(
array(
'name' => 'Humphrey1',
'email' => 'humphrey1#wilkins.com'
),
array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
)
);
$array2 = array(
'name' => 'Humphrey2',
'email' => 'humphrey2#wilkins.com'
);
$print = function ($item, $key) {
echo $key . $item .'<br>';
};
array_walk_recursive($array, $print);
array_walk_recursive($array2, $print);

Restructure an array

I have this array in PHP
$fields = array(
0 => array(
'field1' => 'something1',
'field2' => 'something2'
)
)
And I need it to look like this
$fields = array(
'fields1' => 'something1',
'fields2' => 'something2'
)
What function code can I use to get rid of the 0 index in the example?
You can loop through like this...
Create new array
$newArray = [];
Then loop through
foreach($fields as $field){
if(is_array($field)){
foreach($field as $key => $value){
$newArray[$key] = $value;
}
}
}
just take the '0' element from fields:
$fields=$fields[0];
Simple
$fields = reset($fields);
Or
$fields = array_shift($fields);
Create an array, loop through $fields, and merge whatever items are there with the created array.
$final_array = array();
foreach ($fields as $field)
{
$final_array = array_merge($final_array, $field);
}
$fields = $final_array;
This will be able to handle any number of items in either level of the array and compact them into a one-level array.
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($data)); $list = iterator_to_array($it,false);
Use this to get ride of any extra levels.
Will gives you what you want

Categories