Multi array_merge - php

I'm having a bit of difficulty merging a multi-dimensional array based on 1 index. I don't know if I've just been racking my brain too long and have messed myself up or what, but I can't get this.
An example of 2 indices from 2 arrays is as such:
// Array1:
[0] => Array
(
[appID] => 58510
[name] => SomeRandomApp
[users] => Array
(
[0] => randomUser
)
)
// Array2:
[0] => Array
(
[appID] => 58510
[name] => SomeRandomApp
[users] => Array
(
[0] => anotherUser
)
)
// Desired Result:
[0] => Array
(
[appID] => 58510
[name] => SomeRandomApp
[users] => Array
(
[0] => randomUser
[1] => anotherUser
)
)
I'd like to merge based on "appID" and nothing else. And then do another merge on users so that if another index has different users, they all just merge.

It sounds like you want to get a list of users for each app. I think you will have to loop through them. You could created a result array indexed by the appID like this (not tested):
function app_users($array1, $array2) {
$combined = array ();
foreach (array($array1, $array2) as $arr) {
foreach ($arr as $values) {
if (!isset($combined[$values['appId']])) {
$combined[$values['appID']] = $values;
}
else {
$combined[$values['appID']]['users'][] = $values['users'][0];
}
}
}
}
$result = app_users($array1, $array2);
This assumes the same user won't be listed twice. You can modify the function to handle duplicates if necessary.
As a side note, array_merge will overwrite values in the first array with the second in the case of duplicate keys, which I don't believe is the behaviour you want here.

#Andrew, have you try to use array_merge_recursive() instead?

Finally got it all worked out.
$newArray = array();
foreach($data as $item)
{
$appID = $item['appID'];
$users = $item['users'];
unset($item['users']);
unset($item['hoursOnRecord']);
if(!isset($newArray[$appID]))
{
$newArray[$appID] = $item;
foreach($users as $user)
$newArray[$appID]['users'][] = $user;
}
else
{
$users2 = $newArray[$appID]['users'];
$newArray[$appID] = $item;
foreach($users as $user)
$newArray[$appID]['users'][] = $user;
foreach($users2 as $user)
$newArray[$appID]['users'][] = $user;
}
}
It's pretty sloppy, but it works, and it works pretty damn well if I do say so myself. Haven't benchmarked it yet but I did test it against a pretty heavy array with no real noticeable delay. There's a LOT more data in each index than what I'm showing. All in all, I'm content.
I hope this'll help someone else out.

Related

Getting an element from array in PHP

With the following array, how would I just print the last name?
Preferably I'd like to put it in the format print_r($array['LastName']) the problem is, the number is likely to change.
$array = Array
(
[0] => Array
(
[name] => FirstName
[value] => John
)
[1] => Array
(
[name] => LastName
[value] => Geoffrey
)
[2] => Array
(
[name] => MiddleName
[value] => Smith
)
)
I would normalize the array first:
$normalized = array();
foreach($array as $value) {
$normalized[$value['name']] = $value['value'];
}
Then you can just to:
echo $normalized['LastName'];
If you are not sure where the lastname lives, you could write a function to do this like this ...
function getValue($mykey, $myarray) {
foreach($myarray as $a) {
if($a['name'] == $mykey) {
return $a['value'];
}
}
}
Then you could use
print getValue('LastName', $array);
This array is not so easy to access because it contains several arrays which have the same key. if you know where the value is, you can use the position of the array to access the data, in your case that'd be $array[1][value]. if you don't know the position of the data you need you would have to loop through the arrays and check where it is.. there are several solutions to do that eg:
`foreach($array as $arr){
(if $arr['name'] == "lastName")
print_r($arr['value']
}`

Create multidimensional array from standard array

Most likely I'm doing this wayyyyyy too complicated. But I'm in the need of converting multiple arrays to multidimensional array key's. So arrays like this:
Array //$original
(
[0] => 500034
[1] => 500035 //these values need to become
//consecutive keys, in order of array
)
Needs to become:
Array
(
[50034][50035] => array()
)
This needs to be done recursively, as it might also require that it becomes deeper:
Array
(
[50034][50036][50126] => array() //notice that the numbers
//aren't necessarily consecutive, though they are
//in the order of the original array
)
My current code:
$new_array = array();
foreach($original as $k => $v){ //$original from first code
if((gettype($v) === 'string' || gettype($v) === 'integer')
&& !array_key_exists($v, $original)){ //check so as to not have illigal offset types
$new_array =& $original[array_search($v, $original)];
echo 'In loop: <br />';
var_dump($new_array);
echo '<br />';
}
}
echo "After loop <br />";
var_dump($new_array);
echo "</pre><br />";
Gives me:
In loop:
int(500032)
In loop:
int(500033)
After loop
int(500033)
Using this code $new_array =& $original[array_search($v, $original)]; I expected After loop: $new_array[50034][50035] => array().
What am I doing wrong? Been at this for hours on end now :(
EDIT to answer "why" I'm trying to do this
I'm reconstructing facebook data out of a database. Below is my own personal data that isn't reconstructing properly, which is why I need the above question answered.
[500226] => Array
(
[own_id] =>
[entity] => Work
[name] => Office Products Depot
[500227] => Array
(
[own_id] => 500226
[entity] => Employer
[id] => 635872699779885
)
[id] => 646422765379085
)
[500227] => Array
(
[500228] => Array
(
[own_id] => 500227
[entity] => Position
[id] => 140103209354647
)
[name] => Junior Programmer
)
As you can see, the ID [500227] is a child of [500226], however, because I haven't got the path to the child array, a new array is created. The current parentage only works to the first level.
[own_id] is a key where the value indicates which other key should be its parent. Which is why the first array ([500226]) doesn't have a value for [own_id].
If you want to do something recursively, do it recursively. I hope that's what you meant to do.
public function pivotArray($array, $newArray)
{
$shifted = array_shift($array);
if( $shifted !== null )
{
return $this->pivotArray($array, array($shifted=>$newArray));
}
return $newArray;
}
$array = array(432, 432532, 564364);
$newArray = $this->pivotArray($array, array());
Edit: After the question's edit it doesn't seem to be very relevant. Well, maybe someone will find it useful anyway.

How to not echo array if previous one's key has been echoed already

This is what I get after a print_r($myArray) (wrapped in pre) on my array.
Array
(
[0] => 203.143.197.254
[1] => not/available
)
Array
(
[0] => 40.190.125.166
[1] => articles/not/a/page
)
Array
(
[0] => 25.174.7.82
[1] => articles/not/a/page
)
How would I return or echo just the first two in this case (no regex), given the fact that I would like to only output each array whose [1] value has not been echoed before?
My list as far more entries and $myArray[1] is sometimes the same, I want to skip echoing the same thing.
I have tried array_unique but I can't get it to work as param 1 is expected to be an array.
print_r(array_unique($myArray));
This works. Didn't do a full copy paste job but hopefully you get the idea of the logic
$echoed = array();
foreach($array as $arr) {
if(!in_array($arr[1],$echoed)) {
echo $arr[1];
$echoed[] = $arr[1];
}
}
$echoedBefore = array();
print_r(array_filter($myArray, function($entry) {
global $echoedBefore;
$alreadyEchoed = in_array($entry[1], $echoedBefore);
if (!$alreadyEchoed) {
$echoedBefore[] = $entry[1];
}
return !$alreadyEchoed;
}));

Show Can I pull Each Of These Out Of An Array?

I am having trouble pulling elements out of this multi-dimensional array?
Here is my code below:
$ShowTables = $Con->prepare("SHOW TABLES");
$ShowTables->execute();
$ShowTResults = $ShowTables->fetchAll();
If I print_r($ShowTResults); I get this multi-dimensional array:
Array (
[0] => Array ( [Tables_in_alltables] => userinformation [0] => userinformation )
[1] => Array ( [Tables_in_alltables] => users [0] => users )
)
Foreach new table is loaded it adds another dimension of the array. I want to pull each of the table names, out of the multi-dimensional array into a new array which I can use for future plans.
Would anyone have any ideas?
I have tried 1 foreach Loop; but this served no justice.
You want to fetch all results of the first column in form of an array:
$ShowTResults = $Con->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN, 0);
print_r($ShowTResults);
This gives you:
Array (
[0] => userinformation
[1] => users
)
Which I think is what you're looking for.
Another variant (a bit more complicated, but fitting for similar but little different cases) is to fetch the results as function (PDO::FETCH_FUNC) and directly map the result:
$ShowTResults = $ShowTables->fetchAll(PDO::FETCH_FUNC, function($table) {
return $table;
});
A Solution I tried: Perhaps not as other will do, which is in full respect. But Here is mine:
$DatabaseTables = array();
foreach($ShowTResults AS $ShowTResult)
{
foreach ($ShowTResult AS $ShowT)
{
$DatabaseTables[] = $ShowT;
}
}
$DatabaseTables = array_unique($DatabaseTables); //Deletes Duplicates in Array
unset($ShowTResult);
unset($ShowT); // Free up these variables
print_r($DatabaseTables);

Counting distinct values in a multidimensional array

I have an array that looks like the one below. I'm trying to group and count them, but haven't been able to get it to work.
The original $result array looks like this:
Array
(
[sku] => Array
(
[0] => 344
[1] => 344
[2] => 164
)
[cpk] => Array
(
[0] => d456
[1] => d456
)
)
I'm trying to take this and create a new array:
$item[sku][344] = 2;
$item[sku][164] = 1;
$item[cpk][d456] = 1;
I've gone through various iterations of in_array statements inside for loops, but still haven't been able to get it working. Can anyone help?
I wouldn't use in_array() personally here.
This just loops through creating the array as it goes.
It seems to work without needing to first set the index as 0.
$newArray = array();
foreach($result as $key => $group) {
foreach($group as $member) {
$newArray[$key][$member]++;
}
}

Categories