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.
Related
I'm getting started with PHP and I have some troubles finding a way to output values from multiples arrays sent from an external site.
I did a foreach and the code that is printed looks like this :
Array
(
[id] => 1
[title] => Title 1
)
Array
(
[id] => 2
[title] => Title 2
)
Array
(
[id] => 3
[title] => Title 3
)
Any idea how I could get every id (1,2,3) in an echo?
Let me know if you need more informations!
Thanks a lot!
If you just want to echo all the id's in all the arrays, a simple solution would be:
foreach ([$array1, $array2, $array3] as $arr) {
echo $arr['id'];
}
A better solution would probably to create one main array first:
$mainArray = [];
and every time you get a new array, you just push them to the main array:
$mainArray[] = $array1;
$mainArray[] = $array2;
// ... and so on
Then you'll have a multi dimensional array and can loop them with:
foreach ($mainArray as $arr) {
echo $arr['id'];
}
Which solution that works best depends on how you get the arrays and how many they are.
Note: Using array_merge() as others have suggested will not work in this case, since all the arrays have the same keys. From the documentation on array_merge(): "If the input arrays have the same string keys, then the later value for that key will overwrite the previous one."
As you can do:
$array = array_merge_recursive($arr1, $arr2, $arr3);
var_dump($newArray['id']);
echo implode(",", $newArray['id']);
A demo code is here
The above searching I want with minimum number of code and with best serach performance.
I want to generate an array from this above array by putting logic like:
ALL "EMA" key values of array should not be allowed to match with "JACKSON" key values. Similarly all "JACKSON" key values of the same array are not allowed to fall in any value of "EMA" key. So the resulting array would be like shown below:
Array
(
[0] => Array
(
[EMA] => A
[JACKSON] => B
)
[2] => Array
(
[EMA] => D
[JACKSON] => E
)
)
I want to know the best approach with lesser code to achieve this. The method I have used seems so lengthy. I want a shorter and robust approach.
I think this might be a solution:
$emas = array();
$jacksons = array();
foreach($array as $element){
$emas[] = $element['EMA'];
$jacksons[] = $element['JACKSON'];
}
//array_intersect returns the common values in the arrays as an array
if(!empty(array_intersect($emas, $jacksons))){
echo 'array is invalid!';
}
I am trying to figure out how to reorganize an array..
I have a multidimensional array(Ill call that original_array) and I would like to take the first array within original_array and set the values as keys in a new array. I also want to take the values of the second array in original_array and make them keys and then set the values of the third array in original_array as the values for those keys.
Here is an example of original_array:
Array (
[id] => Array (
[0] => 1
[1] => 3
)
[reward] => Array (
[0] => Movie
[1] => Trip
)
[cost] => Array (
[0] => 50
[1] => 200
)
)
Basically what I would like to do is look like this:
Array (
[1] => Array (
[Movie] => 50
)
[3] => Array (
[Trip] => 200
)
)
Is there a simple and elegant way to merge these like this?
I have spent hours trying to figure this out using array_merge, array_merge_recursive.. etc. And have search SO far and wide for a similar questions, but I haven't found anything that does what I am after.
I was able to correctly combine the 2nd and 3rd arrays in original_array with array_combine. But, I am at a loss as how to combine that result with the 1st array's values in original_array.
Thanks in advance to any help!
Well, the dirty way would be just use combine array functions like array_combine with the input:
$new_array = array_combine(
$array['id'], // parent keys
// combine chunked combined sub keys :p
array_chunk(array_combine($array['reward'], $array['cost']), 1, true)
);
There may be some incantation of array_*() merging functions that could produce what you're looking for, but it is far easier to just iterate over the original array's [id] sub-array and use its values to create new sub-array keys in a different output array.
// To hold your output
$output = array();
// Iterate the original array's [id] sub-array
foreach ($original['id'] as $idxkey => $newkey) {
// Add a sub-array using $newkey to the output array
$output[$newkey] = array(
// Using the index (not value), retrieve the corresponding reward
// value to use as the new array key
// and corresponding cost to use as the new subarray value
$original['reward'][$idxkey] => $original['cost'][$idxkey]
);
}
Here is a demonstration: https://3v4l.org/2pac3
This should work for you:
First you can get the keys for the main array into a separate variable with array_shift(), which will just remove the first element from your array, which is the array holding the keys.
Then use array_map() to loop through both of your subArrays and use reward as key with the cost values as value and return it in an array. At the end you just have to array_combine() your keys $keys with the new created array.
Code:
<?php
$keys = array_shift($arr);
$result = array_combine($keys, array_map(function($k, $v){
return [$k => $v];
}, $arr["reward"], $arr["cost"]));
print_r($result);
?>
You might wanna take a look at BaseArrayHelper from Yii 2.0 Framework.
Although this file is part of a framework it has only very few dependencies and you should be able to use just this file or parts of it in your code with small modifications.
An example for your use case can be found in the index() method.
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);
I have an array that contains entries that themselves contain two types of entries.
For simplicity sake, let's say that the entries are like this:
a|1
b|4
a|2
c|5
b|3
etc.
In fact they represent categories and subcategories in my database.
I will use explode to break these entries into letters and digits.
The question is: I want to group them by category.
What's the easiest way to create a multilevel array, which could be sorted by letters:
a|1
a|2
b|4
b|3
c|5
?
How about something like this?
$input = array('a|1','b|4','a|2','c|5','b|3');
$output = array();
foreach($input as $i){
list($key,$val) = explode("|",$i);
$output[$key][] = $val;
}
Output:
Array
(
[a] => Array
(
[0] => 1
[1] => 2
)
[b] => Array
(
[0] => 4
[1] => 3
)
[c] => Array
(
[0] => 5
)
)
<?php
$your_array = array();
$your_array[a] = array('1','2','3');
$your_array[b] = array('4','5','6');
print_r($your_array);
?>
I take it that your entries are strings (relying on the fact that you want to use explode() on them).
If so you can simply sort the array by using sort($array), and then iterate on that array and explode the values and put them in another array, which will be sorted by the previous array's order.