new array be joining 2 arrays at random - php

Dear stackoverflow members,
I want to join 2 arrays in random as mentioned below, i tried different methods but i was not able to produce the result that i exactly wanted.
I have 2 arrays which looks like this. Lets call this names.
Array
(
[bill] => Array
(
)
[steve] => Array
(
)
[Ritchie] => Array
(
)
)
now these names are generated from another function, it's output looks something like this.
Array
(
[1] => Array
(
[email] => info#bill.com
[name] => bill
[web] => http://bill.com
)
[2] => Array
(
[email] => rich#steve.com
[name] => steve
[web] => http://steve.com
)
[3] => Array
(
[email] => god#linux.com
[name] => Ritchie
[web] => http://linux.com
)
[4] => Array
(
[email] => dummy#dummy.com
[name] => Ritchie
[web] => http://linux.com
)
)
and the 2nd array, lets call it countries.
Array
(
[0] => USA
[1] => UK
[2] => Netherlands
[3] => Australia
[4] => Germany
)
Now here is the exact problem. i want the 1st array names and the 2nd array countries to be joined and form another associative array in random order. But please note that the function which returns the name array returns the key : Ritchie twice, it has 2 occurrences. So the final array should be something like this.
Array
(
[Ritchie] => Array
(
[0] => USA,
[1] => Germany
)
[bill] => Array
(
[0] => Netherlands
)
[steve] => Array
(
[0] => UK
)
)
Since the key Ritchie has 2 occurrences, 2 unique values from the country array should be added. The number of keys or occurrences in names and the keys in countries will always be the same. If their is anything unclear, let me know i'll clear it out.
I did heavy research on the internet and stackoverflow and i was only able to come up with this. The current solution i have is this. Please be kind to help me to improve the current lines of code to suit my need or may be this might not be elegant, if so, please be kind to suggest a better solution.
$jumble = array();
foreach ($names as $name) {
$jumble[$name] = $countries[array_rand($countries)];
}
Thank you.

Try this code:
shuffle($countries);
$n = count($countries); $i = 0;
$jumble = array();
foreach ($names as $name) {
if (!isset($jumble[$name])) $jumble[$name] = array();
$jumble[$name][] = $countries[$i++ % $n];
}
Demo

Related

Extract single index value (from every sub-array) from a multi-Key multidimensional array [duplicate]

This question already has answers here:
Can I get all keys of an multi level associative arrays in php
(5 answers)
Closed last year.
I am trying to create an single-dimension array of 'id's' extracted from a multidimensional array that will vary in depth. I need to extract the value from EACH array (no matter how deep). Each array has been indexed (see below) with the same keys. I have tried flattening so I could use 'array_column' (doesn't work because of the number of keys in each array), as well as methods like print_r(array_keys($data[0])[0]) (doesn't work for unknown dimension depth). It seems simple enough but I'm not finding any examples that are like this. Any direction is appreciated. Thank you.
Array
(
[0] => Array
(
[id] => 1000005
[first_name] => James
[last_name] => Smith
[position_root] => CHF CUST EX
[position_area] => Customer Operations
[items] => Array
(
[0] => Array
(
[id] => 1000134
[first_name] => Brandt
[last_name] => Jones
[position_root] => BS APL PJCTS
[position_area] => Customer Executive Support
[items] => Array
(
)
)
[1] => Array
(
[id] => 1000149
[first_name] => Daniel
[last_name] => Brown
[position_root] => CUST PROG
[position_area] => CUSTOMER PROGRAMS
[items] => Array
(
[0] => Array
(
[id] => 1000060
[first_name] => Duane
[last_name] => Pearson
[position_root] => CUST PRG IN
[position_area] => Customer Program Design
[items] => Array
(
)
)
What I am hoping for is:
[0] => 1000005
[1] => 1000134
[2] => 1000149
[3] => 1000060
... and so on ...
As suggested, you can use array_walk_recursive to achieve this.
<?php
$ids = [];
array_walk_recursive($data,function($value,$key) use (&$ids){
if($key == 'id') $ids[] = $value;
});
print_r($ids);

PHP array formatting issue

I have an array list like
[1] => Array
(
[name] => Linda
[age] => 23
[country] => USA
)
[2] => Array
(
[name] => Fleur
[age] => 16
[country] => France
)
How do I remove the keys [1], [2] from the array so I get an output like
Array
(
[name] => Linda
[age] => 23
[country] => USA
)
Array
(
[name] => Fleur
[age] => 16
[country] => France
)
Any help would be appreciated. I know it seems simple but I'm new to this.
If you want just to print the output you want, you can just do this:
print_r($arr[1]);
print_r($arr[2]);
There's really not a "removal" option since the "1" and "2" keys you have there are exist for sorting your other subarrays which have similar keys (like name).
It's a kind of overwriting..
Even the simplest array like:
$arr = array(5,8);
is in fact:
Array
(
[0] => 5
[1] => 8
)
loop though and do each one individually
foreach($array as $val) {
print_r($val);
}
Any element of an array is a key-value pair.
So you can't have an item without key.
If it's just a matter of output, please do not use var_dump() as a way to output things to your end-user.
You can simply iterate through your main array with a foreach loop, and display items in a user-friendly way.

PHP: Pull values foreach() nested array, run function, return a 2nd level nested array

I've got an array that looks like this:
Array
(
[0] => Array
(
[id] => abc
[name] => Charlotte
[state] => NC
)
[1] => Array
(
[id] => def
[name] => Tampa
[state] => FL
)
)
What I am trying to do is pull two of the values from each nested array ('id' and 'name'), run a function on them, and return an array that is then nested. So, for each 'id' and 'name,' pass that to "function work($id,$name)," which returns an array, such that the resulting array looks like this:
Array
(
[0] => Array
(
[id] => abc
[name] => Charlotte
[state] => NC
[restaurants] => Array (
[rname] => Good Burger
[rname] => McD
)
)
[1] => Array
(
[id] => def
[name] => Tampa
[state] => FL
[restaurants] => Array (
[rname] => BK
[rname] => White Castle
)
)
)
My searches on here found a few ways of pulling the values from the original arrays (foreach() loop), but I am unsure of the best way to pass these values to a function (array_walk doesn't appear to be an option in this case?), and especially of how to return a nested array into another nested array.
Am glad to provide clarification is need be.
foreach ($array as $key => $value){
$array[$key]['restaurants'] = work($value['id'],$value['name']);
}
function work($id,$name){
$results = array();
///process data
return $results;
}
Try something like this:
foreach($cities as &$city){
$city['restaurants'] = work($city['id'],$city['name']);
}
Demo with a dummy function.
The &$city tells PHP that you want to be able to modify the record in your loop (passes the array by reference instead of as a copy).
After this, you can simply set the restaurants value to the array returned by the work function.

Sort array according to the search string occurence php

I want to sort two dimensional array according to the occurrence of the search string in php. i tried to fetch data according to the relevance of search string . i come across match and against but it will work on the MYISAM but my table is in innodb. so plan to sort the array using any sort function but i cant find out anything.
my search pressure tes string array
Array
(
[0] => pressure
[1] => tes
)
My output array which matches the above string with title is
Array
(
[0] => Array
(
[title] => tests.doc
[link] => http://localhost/test.doc
[snippet] =>
)
[1] => Array
(
[title] => Pressure Testing Your Company
[link] => http://localhost/Pressure_Testing_Your_Companys.pdf
[snippet] => Questions used by the CFO against dimensions critical to success
)
[2] => Array
(
[title] => pressure.doc
[link] => http://localhost/pressure.doc
[snippet] => Templates for services
)
)
In the above array the most relevant array[1] then array[2] and then array[0] should be in this order. i want to sort this array accordingly. my output should be like below:
Array
(
[0] => Array
(
[title] => Pressure Testing Your Company
[link] => http://localhost/Pressure_Testing_Your_Companys.pdf
[snippet] => Questions used by the CFO against dimensions critical to success
)
[1] => Array
(
[title] => pressure.doc
[link] => http://localhost/pressure.doc
[snippet] => Templates for services
)
[2] => Array
(
[title] => tests.doc
[link] => http://localhost/test.doc
[snippet] =>
)
)
please help me!!!!
Look at the example #3, I think that's what you want.
http://php.net/manual/en/function.array-multisort.php
Just tested this, it seems to be working :
$titles = array();
foreach ( $array as $key => $value )
{
$titles[ $key ] = $value['title'];
}
array_multisort( $titles, SORT_ASC , $array );
I would highly recommend to sort your results in your MySQL query, that would be much better performance wise.

How to get key of second argument in in_array?

I have an array (array01) that contains a bunch of sub arrays consisting of two pieces of data each, like:
Array ( [0] => Array ( [0] => 10CC [1] => Dreadlock Holiday )
[1] => Array ( [0] => 10CC [1] => I\'m Not In Love )
[2] => Array ( [0] => 10CC [1] => Dreadlock Holiday ) )
etc...
I have another array (array02) like:
Array ( [66] => Array ( [0] => 10CC [1] => Dreadlock Holiday )
[585] => Array ( [0] => 10CC [1] => I\'m Not In Love )
etc...
I'm successfully using foreach and then in_array to see what array01 elements are in array02. However, what I am struggling to figure out is how to get the id of what element in array2 the hit was on.
So for example, array01's 0 and 2 elements (both 10CC, Dreadlock Holiday), are matched in array02, but how do I get the ID of the element (in this case, 66)?
Thanks for your help.
Have you tried the array_search function?
look for documentation for the array_intersect() in PHP manual. Note that the original keys are preserved so it returns an array with the elements present on the array02 array with the original keys.
Hope it's what you're looking for
Cheers

Categories