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

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

Related

How to put keys in array?

I am scrapping details from a certain website. Then I want to parse HTML into a PHP array.
I want to display the array like this. I need to add key so that I can determine easily what data I want to use in the future.
[info] => Array
(
[0] => info1
[1] => info2
)
Here is my code:
$hk = array('info');
foreach($html->find('div[id="home"] div[id="topinfo"] p') as $home) {
$hometps[] = $home->plaintext;
}
print_r(array_fill_keys($hk,$hometps));
But output will show me this:
Array
(
[info] => Array
(
[0] => info1
[1] => info2
)
)
Array element cannot stand on its own. Considering you want info as an index, it has to be a part of an array.
If you want the list of info available then assign them to $info variable and when you print_r($info), like this:
$info = array();
foreach($html->find('div[id="home"] div[id="topinfo"] p') as $home) {
$info[] = $home->plaintext;
}
print_r($info);
And you will get:
Array
(
[0] => info1
[1] => info2
)
Looks like you might be trying to rename the representation value in the array also known as the 'key' I guess. I recommend doing that directly to the output of the html while going into the foreach. That should solve your issue. It would look something like this(original example at bottom):
$hk = array('info');
foreach($html->find('div[id="home"] div[id="topinfo"] p') as $hk => $home) {
$hometps[] = $home->plaintext;
}
print_r($hometps);
foreach (array_expression as $key => $value)
statement
The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).
The second form will additionally assign the current element's key to the $key variable on each iteration.
PHP.net:foreach
I think everybody is confused about the issue and question here. The following will give you an array named $info, which will hold the returned values of the foreach loop:
$info = Array();
foreach($html->find('div[id="home"] div[id="topinfo"] p') as $home) {
array_push($info,$home->plaintext);
}
print_r($info);
This will output:
Array (
[0] => info1
[1] => info2
)
Hope this was what you were trying to achieve.

Compare 2 arrays on single element in php

I have two arrays that look like this with many more results:
Array
(
[0] => Array
(
[comName] => John
[locID] => L152145
[locName] => Johns House
)
)
What i'd like to do is compare the results but only on the locName element...here is the code i'm working with thus far.
$searchcode = "a url to json results";
$simple = file_get_contents($searchcode);
$arr = json_decode($simple , true);
do this for each json file then
$result = array_intersect($arr, $anotherarr);
Ideally this would return the matching locNames from both arrays
Thanks for the help!
What you are a looking for is function array_uintersect:
$result = array_uintersect($arr, $anotherarr, function($a, $b) { return strcmp($a['locName'], $b['locName']); });
If each locName will appear only once, then I suggest you transform your array in an associative one in the form
Array
(
[Johns House] => Array
(
[comName] => John
[locID] => L152145
[locName] => Johns House
)
)
This way, you'll have access to every location name using array_keys, and will be able to pick the locations that are present in both arrays with a simple array_intersect on both array_keys.
The simplest way to do this is to iterate over the original array filling a new one (not really efficient if you're planning to manage 10000+ elements, but negligible in other case)
$assocA=array();
$assocB=array();
foreach($arr as $element) {
$assocA[$element['locName']]=$element;
}
foreach($anotherarr as $anotherelement) {
$assocB[$anotherelement['locName']]=$anotherelement;
}
$common_locations = array_intersect(array_keys($assocA), array_keys($assocB)); // will return all locnames present in both arrays.

Having trouble building single array from while loop in PHP

I am trying to build an array from entries in a MySQL database. I have connected to the database just fine, and I have a foreach loop which pulls the entries from the database based on the quantity of items like so:
$totalMarkers = count($results);
foreach($results as $result){
$gpsLats[] = $result->gpslat;
$gpsLongs[] = $result->gpslong;
}
I then need to take these entries and run them through a while loop to attempt to build my array:
$it = 0;
while ($it < $totalMarkers) {
$incr = $it++;
$myLatitudes = $gpsLats[$incr];
$myLongitudes = $gpsLongs[$incr];
$items = array($myLatitudes,$myLongitudes);
print_r($items);
}
The problem is that the output looks something like this:
Array ( [0] => 54.8607 [1] => -32.4135 )
Array ( [0] => 39.8460 [1] => -87.4166 )
Array ( [0] => 78.8403 [1] => -95.4156 )
Really what I need is for all the entries to be contained in one array statement. I have a good feeling that I am overcomplicating this, but I need a nudge in the right direction. Thanks for your time in looking into this.
You forgot the array 'append' operation:
$items[] = array($myLatitudes,$myLongitudes);
^^--- missing
Without the [], you're simply creating a two-item array and overwriting it on every loop iteration.

php check if all values from one two dimensional array are in another two dimensional array

I have a two, two dimensional arrayw like this. They are dynamicly created so they can have different numbers of arrays inside.
$userInput['shops'] = Array
(
[0] => Array
(
[id] => 9
)
)
and another that look like this:
$userShops = Array
(
[0] => Array
(
[id] => 9
)
[1] => Array
(
[id] => 10
)
)
First array is something that i receve from post, ids of selected shops. Second array shows all ids of shops that user have. How can i test if all values from userInput can be found in array userShops? I use this for validation so i need to see if all values from post matches the real values for user.
I have tried to do it like this but i receve oknot as result, so i think this should be constructed differently, maybe to somehow count matches...You should ignore my code because i think this is bad approach...In short i need to check if all values from first array can be found in second, if not than show an error.
if(isset($userInput['shops']) && is_array($userInput['shops'])){
foreach($userInput['shops'] as $input){
foreach($userShops as $userShop){
if(in_array($input, $userShop)){
print_r('ok');
}
else {
print_r('not'); or show validation error
}
}
}
exit;
}
How about something like this:
function flatten(array $data) {
return array_map(function(array $element) {
return $element['id'];
}, $data);
}
$user = flatten($userInput['shops']);
$shops = flatten($userShops);
$isCovered = empty(array_diff($user, $shops));

Multi array_merge

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.

Categories