Check if array contains child array and merge in parent array - php

I want to do :
Check if array contains array.
If parent array contains child array then interchange the key and value of child array.
Update all keys of child array to '1'. i.e. value of child array after interchange key and value
Delete child array and merge its element to parent array.
Example:
Generated array:
array
'first_name' => string 'sushil' (length=6)
'last_name' => string 'asfasfaf' (length=8)
'gen' => string 'Male' (length=4)
'language' => string 'PHP' (length=3)
'biodata' => string 'sfsafsaf hdffd ' (length=15)
'hobbies' =>
array
0 => string 'gaming' (length=6)
1 => string 'football' (length=8)
2 => string 'cricket' (length=7)
'academic_qualification' => string 'Bachelor' (length=8)
I want to modify as above step:
//finds if child array exists. If exists interchange key and value and update value to '1'.
array
'gaming' => int 1
'football' => int 1
'cricket' => int 1
And finally unset original child array and merge modified child array's element to parent array.
My expected array form:
array
'first_name' => string 'sushil' (length=6)
'last_name' => string 'asfasfaf' (length=8)
'gen' => string 'Male' (length=4)
'language' => string 'PHP' (length=3)
'biodata' => string 'sfsafsaf hdffd ' (length=15)
'academic_qualification' => string 'Bachelor' (length=8)
'gaming' => int 1
'football' => int 1
'cricket' => int 1
I tried like following but its not working:
$submited_data = $_POST;
var_dump($submited_data);
foreach($submited_data as $value){
if(is_array($value)) { //checks if array contains array.
$a = array_flip($value); //then interchange
var_dump($a);
foreach($a as $key=>$b){
$a[$key] = 1; //update all value to '1'.
}
array_push($submited_data,$a); // here is the problem I cannot proceed to furthur step. Please help me. How to merge modified child array to parent array.
var_dump($a);
}
}
Thank You.

Ive just rewritten your code a bit. Please tell me if anything goes wrong!
<?php
$submited_data = $_POST;
foreach($submited_data as $key => $data)
{
if(is_array($data))
{
foreach($data as $sub_data)
{
$submited_data[$sub_data] = 1;
}
unset($submitted_data[$key]);
}
}

suppose $array is the array with child array,
$mergedArray = [];
array_walk_recursive($array, function($a,$b) use (&$mergedArray) { $mergedArray[$b] = $a; });
echo '<pre>';
print_r($mergedArray);
echo '</pre>';

Related

php array count values in 4 deep array

Im trying to count how many times a delivery date is in my array but i seem to only be able to count the first level.
array (size=48)
'2000-01-01' =>
array (size=2)
'date' => string '2000-01-01' (length=10)
0 =>
array (size=2)
'van' => string '0' (length=1)
0 =>
array (size=619)
'drop' => string '0' (length=1)
0 =>
array (size=29)
'id' => string '18137' (length=5)
'order_number' => string '13550' (length=5)
'reference' => string '' (length=0)
'delivery_date' => string '2000-01-01' (length=10)
I've tried:
$counts = array_count_values(array_flip(array_column($output, 'delivery_date')));
and
$array = array_map(function($element){
return $element['delivery_date'];
}, $output);
$array2 = (array_count_values($array));
print_r($array2);
in the end i either end up with a array to string error or the value 1.
how Would i go about counting these?
Thanks.
You could make use of array_walk_recursive and increment an array value every time the delivery_date key is present in the array at any level:
$counts = [];
array_walk_recursive(
$output,
static function ($value, string $key) use (&$counts): void {
if ($key === 'delivery_date') {
$counts[$value] = ($counts[$value] ?? 0) + 1;
}
}
);

Convert array index to custom value?

I have an array $indexedarray
printr($indexedarray) gives something like this
array (size=3)
0 => string 'Homes' (length=5)
1 => string 'Apartments' (length=10)
2 => string 'Villas' (length=6)
I want to change this arrays index also same as value, like
array (size=3)
'Homes' => string 'Homes' (length=5)
'Apartments' => string 'Apartments' (length=10)
'Villas' => string 'Villas' (length=6)
is it posssible??
You can use array_combine:
$indexedarray= ['Homes', 'Apartments', 'Villas'];
print_r(array_combine($indexedarray, $indexedarray));
Gives:
Array
(
[Homes] => Homes
[Apartments] => Apartments
[Villas] => Villas
)
But be aware that your duplicate values will be dropped. Keys will be unique!
Try This :
$myArray = [
0 => 'Homes',
1 => 'Apartments',
2 => 'Villas' ];
$newArray = [];
foreach($myArray as $key => $value){
$newArray[$value] = $value;
}
var_dump($newArray);

Php Convert Multidimensional array to string

Below is my function:
public function getChildrenId(){
$child_id = array($this->db->query("SELECT customer_id
FROM " . DB_PREFIX . "customer
WHERE parent IN ( " .(int)$this->customer->getId().") "));
foreach($child_id as $id =>$value) {
$conv = json_decode(json_encode($value), true);
$final = array_slice($conv,2);
foreach ($final as $gchildren => $key) {
sort($key);
$gr = array_slice($key,0,$this->INF);
}
}
return $gr;
}
It outputs:
array (size=3)
0 =>
array (size=1)
'customer_id' => string '2' (length=1)
1 =>
array (size=1)
'customer_id' => string '4' (length=1)
2 =>
array (size=1)
'customer_id' => string '7' (length=1)
I am trying to get the values of the nested arrays. When I use foreach I only get data from array[0]. I also tried slicing the parent array and still didn't get it right, it outputs array,array,array.
I would like to extract these arrays values to a new array that I can use to query the database. final_array = array (2,4,7).
Thank you in advance!
If your array looks like this, then the foreach should create the array your looking for.
array (size=3)
0 =>
array (size=1)
'customer_id' => string '2' (length=1)
1 =>
array (size=1)
'customer_id' => string '4' (length=1)
2 =>
array (size=1)
'customer_id' => string '7' (length=1)
The following php will output array(2,4,7);
<?php
$aNewArray = array();
foreach($aArray as $aArray){
$aNewArray[] = $aArray['customer_id'];
}
var_dump($aNewArray);
?>
You dont need a multidimensional array for this though.

get parent array name after array_walk_recursive function

I use the following function to verify if a search word is in the name of files of my folder.
$files2=list_files("documents/minelli");
Class Commentaire_filter{
static function test_print($item, $key, $value)
{
if (preg_match("#".$value."#", $item))
{
$array = Array($key=>$item);
print_r($array);
?>
<?php echo $key.' '. $item; ?><br />
<?php
}
}
}
array_walk_recursive($files2, 'Commentaire_filter::test_print',$motrecherche );
I obtain a list of files.
I would like add a link to permit users to download the file.
When i'm using the array_walk_recursive function, i can only get the name of file and the key. How can i get the name of parent arrays to made the link ?
Here an extract of my $files:
array (size=5)
'Administratifs' =>
array (size=5)
0 => string 'campagne-sanmarina.jpg' (length=22)
1 => string 'COSMO Echantillons ETE 2009.xls' (length=31)
2 => string 'COSMOPARIS Echantillons MARO Hiver 2011 311-411.xls' (length=51)
3 => string 'cosmoparis-boutique.jpg' (length=23)
4 => string 'minelli-20-ans.png' (length=18)
'Commerce' =>
array (size=4)
0 => string 'a-gagner-cosmoparis.jpg' (length=23)
1 => string 'CONTROLE 2009.pdf' (length=17)
2 => string 'cosmoparis-boutique.jpg' (length=23)
3 => string 'soldes-cosmoparis.jpg' (length=21)
'Gestion' =>
array (size=1)
'PROCEDURES' =>
array (size=5)
0 => string 'cosmoparis-boutique.jpg' (length=23)
1 => string 'flux-ecommerce-smc.pdf' (length=22)
2 => string 'Minelli-Lyon.jpg' (length=16)
3 => string 'sanmarina-magasin-interieur.jpg' (length=31)
4 => string 'visuel_chaussures_minelli_printemps_ete_2009.jpg' (length=48)
'Magasins' =>
array (size=2)
0 => string 'COSMO Echantillons ETE 2009.xls' (length=31)
1 => string 'san-marina-saint-etienne.jpg' (length=28)
'Ressources Humaines' =>
array (size=7)
'ACTUALITES PAYE' =>
array (size=3)
0 => string 'COSMOPARIS Echantillons MARO Hiver 2011 311-411.xls' (length=51)
1 => string 'cosmoparis-boutique25.jpg' (length=23)
2 => string 'minelli-tours.jpg' (length=17)
...
For 'cosmoparis-boutique25.jpg', i would like to get the parent array name ('Ressources Humaines'=>'ACTUALITES PAYE'). How can i get this information to build a link like 'myfolder/Ressources Humaines/ACTUALITES PAYE/cosmoparis-boutique25.jpg ?
Thank you for your help!
You will have to ditch array_walk_recursive and roll your own recursive walk. This will allow you to maintain or pass custom state information whenever you recurse.
For example:
function my_walk_recursive(array $array, $path = null) {
foreach ($array as $k => $v) {
if (!is_array($v)) {
// leaf node (file) -- print link
$fullpath = $path.$v;
// now do whatever you want with $fullpath, e.g.:
echo "Link to $fullpath\n";
}
else {
// directory node -- recurse
my_walk_recursive($v, $path.'/'.$k);
}
}
}

count from several multidimensional arrays

i have foreach, which generate following arrays:
==== array 1 ====
array
0 =>
array
'tag' => string 'daf' (length=3)
1 =>
array
'tag' => string 'daa' (length=3)
2 =>
array
'tag' => string 'daf' (length=3)
3 =>
array
'tag' => string 'daaa' (length=4)
4 =>
array
'tag' => string 'daf' (length=3)
5 =>
array
'tag' => string 'daa' (length=3)
6 =>
array
'tag' => string 'daf' (length=3)
7 =>
array
'tag' => string 'daf' (length=3)
8 =>
array
'tag' => string 'daf' (length=3)
9 =>
array
'tag' => string 'abd' (length=3)
10 =>
array
'tag' => string 'abdaa' (length=5)
11 =>
array
'tag' => string 'abda' (length=4)
==== array 2 ====
array
0 =>
array
'tag' => string 'daf' (length=3)
1 =>
array
'tag' => string 'test1' (length=5)
As output i want to get something like:
array
'daf' => '7'
'daa' => '2'
'daaa' => '1'
'abd' => '1'
'abdaa' => '1'
'abda' => '1'
'test1' => '1'
The value of the new array is the count of the element from all aray generatet from the loop. array_count_values() doesn't work here...any suggestions, how to solve the problem?
Did not notice it was 2 dimensional array.
Here is another code.
var_export(
array_count_values(
call_user_func_array('array_merge', array_merge($array1, $array2))
)
);
Something a bit like this should work:
$result = array();
foreach (array_merge($array1, $array2) as $item) {
$name = $item['tag'];
if (!isset($result[$name])) {
$result[$name] = 0;
}
$result[$name]++;
}
Let's make some use of the Standard PHP Library (SPL).
You can "flatten" an array with an RecursiveArrayIterator and RecursiveIteratorIterator. As a result you get an iterator that visits each leaf of your n-dimensional array and still let's you access the actual key of the element. In the next step concat both RecursiveIteratorIterators with an AppendIterator acting like a single interator that visits each element in all of its inner (appended) iterators.
$ai = new AppendIterator;
$ai->append(new RecursiveIteratorIterator(new RecursiveArrayIterator($array1)));
$ai->append(new RecursiveIteratorIterator(new RecursiveArrayIterator($array2)));
$counters = array();
foreach($ai as $key=>$value) {
if ( 'tag'===$key ) {
// # because I don't care whether this array element exists beforehand or not.
// $value has to be something that can be used as an array key (strings in this case)
#$counters[$value] += 1;
}
}
If you want you can even use a FilterIterator instead of the if('tag'===$key). But imho this doesn't increase the readability/value of the code ;-)

Categories