Flatten array while keeping into account the parent keys [duplicate] - php

This question already has answers here:
Turning multidimensional array into one-dimensional array [duplicate]
(11 answers)
Closed 4 years ago.
I need to flatten an array while making sure that there are no duplicate keys.
For instance let's say I have this:
$arr = array(
$foo = array(
'donuts' => array(
'name' => 'lionel ritchie',
'animal' => 'manatee',
)
)
);
I need a flattened array that looks like this:
$arr = array(
'donuts name' => 'lionel ritchie',
'donuts animal' => 'manatee',
);
It needs to work even if we have more than 1 parent keys.
I have the following code, but I am not sure I can work with this.
foreach (new RecursiveIteratorIterator(new RecursiveArrayIterator($array1)) as $k=>$v){
$array1c[$k] = $v;
}

It's very simple to do, just make it like this:
$arr = array(
$foo = array(
'donuts' => array(
'name' => 'lionel ritchie',
'animal' => 'manatee',
)
)
);
// Will loop 'donuts' and other items that you can insert in the $foo array.
foreach($foo as $findex => $child) {
// Remove item 'donuts' from array, it will get the numeric key of current element by using array_search and array_keys
array_splice($foo, array_search($findex, array_keys($foo)), 1);
foreach($child as $index => $value) {
// Adds an array element for every child
$foo[$findex.' '.$index] = $value;
}
}
Result of var_dump($foo); will be:
array(2) {
["donuts name"]=>
string(14) "lionel ritchie"
["donuts animal"]=>
string(7) "manatee"
}
Just try :)

Related

Group array data by first character and create subarrays in each group [duplicate]

This question already has answers here:
How to display an Array under alphabetical letters using PHP?
(6 answers)
Closed 8 months ago.
I have an array something like this:
$array = array(
'Actual Hours' => 'http://www.example.com/actual',
'Algorithm' => 'http://www.example.com/algorithm',
'Time Clock App' => 'http://www.example.com/time',
)
And I want the output something like this:
Array
(
[A] => [
[Actual Hours] => http://www.example.com/actual
[Algorithm] => http://www.example.com/algorithm
],
[T] => [
[Time Clock App] => http://www.example.com/time
],
)
So basically I want something like this ..
As you can see, I want the first letter of the array key and want to sort it by adding a new key and group it that way.
Here you go !
$array = array(
'Actual Hours' => 'http://www.example.com/actual',
'Algorithm' => 'http://www.example.com/algorithm',
'Time Clock App' => 'http://www.example.com/time',
);
$new_array = [];
foreach( $array as $key => $value ) {
$char = strtoupper(substr($key,0,1));
if(!array_key_exists( $char, $new_array)) {
$new_array[$char] = [];
}
$new_array[$char][$key] = $value;
}
$array = $new_array;
Loop, get the first letter 0 of the key string and add to that with the whole key:
foreach($array as $k => $v) {
$result[strtoupper($k[0])][$k] = $v;
}

Echo Array Values in Comma Separated List [duplicate]

This question already has answers here:
Implode a column of values from a two dimensional array [duplicate]
(3 answers)
Closed 7 months ago.
I am selecting values from my database, when I dump the $results I get;
array (
0 =>
(object) array(
'FieldName' => 'certification_name',
'FieldValue' => 'White Belt',
),
1 =>
(object) array(
'FieldName' => 'certification_name',
'FieldValue' => 'Yellow Belt',
),
)
I want to display the following on my page;
Certification List: White Belt, Yellow Belt
I have created a loop but when I echo the result I get this;
Certification List: Array Array
My PHP code;
foreach ($results as $result) {
$name = $result->FieldName;
$value = $result->FieldValue;
$items[] = array(
'name' => $name,
'value' => $value
);
}
$items = implode("\n", $items);
echo 'Certification List: ' .$items;
What do I need to change in order to get this working?
You shouldn't push arrays into $items, just push the values.
foreach ($results as $result) {
$items[] = $result->FieldValue;
}
$item_list = implode(", ", $items);
echo "Certification List: $item_list";
You can also replace the loop with:
$items = array_column($results, 'FieldValue');

Checking to see if a variable exists in an array with in_array [duplicate]

This question already has answers here:
PHP multidimensional array search by value
(23 answers)
Closed 7 years ago.
I'm using in_array to see if $appid is contained in the variable $r. Here is my print_r of the array $r (the appids in the array are always changing):
$array = array(0 =>
array(0 => 356050, 'appid' => 356050),
1 => array(0 => 338040, ' appid' => 338040),
2 => array(0 => 263920, 'appid' => 263920),
3 => array(0 => 411740, 'appid' => 411740)
);
$appid is equal 263920 which is contained in $r array, yet despite the criteria being met 'it works' is not being echoed. Any help would be appreciated as I don't understand what's flawed about my php statement.
if (in_array($appid, $r)) {
echo 'it works'; // criteria met
}
You have an array containing arrays. The function in_array() looks at the content of the outer array, without recursing into inner arrays. It would find something if you did
if (in_array(array(0 => $appid, 'appid' => $appid), $r) {
echo 'It works';
}
You can achieve this using.
function searchAppID($id, $array) {
foreach ($array as $key => $val) {
if ($val['appid'] === $id) {
return $key;
}
}
return null;
}
This will work. You should call it like this:
$id = searchAppID('263920 ', $r);
If you have n-level of array then you can use above function with little modifications.
Please let me know if you need it.
This is an old way, but this will work.
since your input is a multidimensional array, you need to loop through the array and search if the value is in array.
<?php
$array = array(0 =>
array(0 => 356050, 'appid' => 356050),
1 => array(0 => 338040, ' appid' => 338040),
2 => array(0 => 263920, 'appid' => 263920),
3 => array(0 => 411740, 'appid' => 411740)
);
foreach ($array as $value) {
if (in_array($appId, $value)) {
echo 'Found';
}
}
?>
Key specific search with return data: How to search by key=>value in a multidimensional array in PHP
I hope this helps.

How to randomly loop through first layer of nested associative array in PHP?

I have a nested assocative array which might look something like this:
$myarray = array(
['tiger'] => array(
['people'], ['apes'], ['birds']
),
['eagle'] => array(
['rodents'] => array(['mice'], ['squirrel'])
),
['shark'] => ['seals']
);
How can I loop through the first layer (tiger, eagle, shark) in a random order and ensure that I cover them all in my loop? I was looking at the PHP function shuffle();, but I think that function messes up the whole array by shuffling all layers.
You can randomly sort an array like this, it will keep the keys and the values
<?php
$myarray = array(
'tiger' => array(
'people', 'apes', 'birds'
),
'eagle' => array(
'rodents' => array('mice', 'squirrel')
),
'shark' => 'seals'
);
$shuffleKeys = array_keys($myarray);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key) {
$newArray[$key] = $myarray[$key];
}
print_r($newArray);
You can get the keys using array_keys(). Then you can shuffle the resulting key array using shuffle() and iterate through it.
Example:
$keys = array_keys($myarray);
shuffle($keys);
foreach ($keys as $key) {
var_dump($myarray[$key]);
}
According to my test, shuffle only randomizes 1 layer. try it yourself:
<?php
$test = array(
array(1,2,3,4,5),
array('a','b','c','d','e'),
array('one','two','three','four','five')
);
shuffle($test);
var_dump($test);
?>

Transpose 2D array structure [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 6 months ago.
I don't think this can be done (with out my own function), however I'll ask any way.
I have a array in PHP like
array(
'item1' => array(
'Hello',
'Good',
),
'item2' => array(
'World',
'Bye',
),
)
The individual fields come from a web form
I want to rearrange it to the following
array(
array(
'item1' => 'Hello',
'item2' => 'World',
),
array(
'item1' => 'Good',
'item2' => 'Bye',
),
)
Make an array of objects from the field arrays
I could write a function to do this.
However I was wondering can one of the built-in array functions achieve this for me?
There is no built in function to do this - but here is a user-defined one that will:
function convert_array ($array) {
$result = array();
foreach ($array as $key => $inner) {
for ($i = 0; isset($inner[$i]); $i++) {
$result[$i][$key] = $inner[$i];
}
}
return $result;
}
See it working
Most certainly not the most efficient, but as close to "one function" as you'll get. ;)
array_map(function ($i) use ($array) { return array_combine(array_keys($array), $i); }, call_user_func_array('array_map', array_merge(array(function () { return func_get_args(); }), $array)));
See http://codepad.viper-7.com/xIn3Oq.
No. There is no built in function that would do this.

Categories