Php two different array with same keys - php

I am new to php and still learning the language,
let say I have two array
For Example
Array
(
[house_id] => 6
[name] => Lake Villa
[floor] => 5
[unit] => 25
)
Array
(
[house_id] => 6
[name] => Lake Villa
[floor] => 5
[unit] => 25
[parking_id] => 9
[resident_count] => 4
)
How do i get the keys of 1st array onto second, what i am saying is, i just need house_id, name, floor, unit from second array and discard rest of the information.
However, they key is not same and dynamic, which means the first array key whatever returned is also present on second but with additional information. The information above is just an example and the keys might varies but whatever key on first array contains on second array too.
I tried this, but isn't working:
foreach($arr1 as $k=>$v) {
foreach($arr2 as $j=>$w) {
if(isset($arr2[$k]))
$arr[$k] = $w;
}
}

You could use array_intersect_key, to merge the arrays.
$newArray = array_intersect_key($array2, $array1);

Use array_intersect_key().
array_intersect_key() returns an array containing all the entries of
array1 which have keys that are present in all the arguments.
Code
var_dump(array_intersect_key($array1, $array2));

foreach($arr2 as $key=>$val){
if(!array_key_exists($key,$arr1))
unset($arr2[$key]);
}

change condition from
if(isset($arr2[$k]))
to
if($arr1[$k] == $arr2[$j]) // it will work.
and isset is used for checking the variable is set or not.

Try this:
foreach($arr2 as $k=>$v) {
//Check if key is in first array
if(!isset($arr1[$k])) {
//Key not in first array, remove from second array.
unset($arr2[$k]);
}
}

try this
$result_array = array_intersect_key($arr2, $arr1);

Related

PHP - unset array where Key is X and Value is Y

I have this type of array,
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
[1] => Array --> I want to remove this value using its index, which is "1"
(
[id] => 2
[fams] => 5
)
)
I want to remove that array [1] entirely, using its index, so the condition is - where the ID is match, for example - [id] => 2
Is that possible, to remove a particular value with that specific condition?
and without looping (or any similar method that need to loop the array)
thanks in advance!
FYI - I did try to search around, but, to be honest, I'm not sure what "keyword" do I need to use.
I did try before, but I found, array_search, array_keys - and it seems those 2 are not.
I'm okay, if we need several steps, as long as it did not use "loop" method.
---update
I forgot to mention, that I'm using old PHP 5.3.
array_filter should work fine with PHP 5.3.
The downside of this approach is that array_filter will (internally) iterate over all your array's entries, even after finding the right one (it's not a "short-circuit" approach). But at least, it's quick to write and shouldn't make much of a difference unless you're dealing with very big arrays.
Note: you should definitely upgrade your PHP version anyway!
$array = array (
0 =>
array (
'id' => 0,
'fams' => 5
),
1 =>
array (
'id' => 2,
'fams' => 5
)
);
$indexToRemove = 2;
$resultArray = array_filter($array, function ($entry) use ($indexToRemove) {
return $entry['id'] !== $indexToRemove;
});
Demo: https://3v4l.org/6DXjl
You can use array_search to find the key of a sub-array that has a matching id value (extracted using array_column), and if found, unset that element:
if (($k = array_search(2, array_column($array, 'id'))) !== false) {
unset($array[$k]);
}
print_r($array);
Output:
Array
(
[0] => Array
(
[id] => 0
[fams] => 5
)
)
Demo on 3v4l.org
It should be noted that although there is no explicit loop in this code, array_search and array_column both loop through the array internally.
You can use array_column to make id as index of the sub-array then use unset
$a = array_column($a, null, 'id');//new array id as index
$index = 2;// id to remove
if($a[$index]) unset($a[$index]);
print_r($a);
Working example :- https://3v4l.org/ofMr7

Get value from different arrays

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

How do I reorganize an array in PHP?

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.

Two PHP arrays, unset positions that are only present in one array

I have two arrays (in PHP):
ArrayA
(
[0] => 9
[1] => 1
[2] => 2
[3] => 7
)
ArrayB
(
[0] => 1
[1] => 1
[3] => 8
)
I want to make two new arrays, where I have only the elements declared in both of the arrays, like the following:
ArrayA
(
[0] => 9
[1] => 1
[3] => 7
)
ArrayB
(
[0] => 1
[1] => 1
[3] => 8
)
In this example ArrayA[2] doesn't exist, so ArrayB[2] has been unset.
I wrote this for loop:
for ($i = 0, $i = 99999, $i++){
if (isset($ArrayA[$i]) AND isset($ArrayB[$i]) == FALSE)
{
unset($ArrayA[$i],$ArrayB[$i]);
}
}
But it's not great because it tries every index between 0 and a very big number (99999 in this case). How can I improve my code?
The function you're looking for is array_intersect_key:
array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all the arguments.
Since you want both arrays, you'll have to run it twice, with the parameters in opposite orders, as it only keeps keys from the first array. An example:
$arrayA_filtered = array_intersect_key($arrayA, $arrayB);
$arrayB_filtered = array_intersect_key($arrayB, $arrayA);
Also, although a for loop wasn't ideal in this case, in other cases where you find yourself needing to loop through sparse array (one where not every number is set), you can use a foreach loop:
foreach($array as $key => $value) {
//Do stuff
}
One very important thing to note about PHP arrays is that they are associative. You can't simply use a for loop, as the indices are not necessarily a range of integers. Consider what would happen if you applied this algorithm twice! You'd get out of bounds errors as $arrayA[2] and $arrayB[2] no longer exist!
I would iterate through the arrays using nested foreach statements. I.e.
$outputA = array();
$outputB = array();
foreach ($arrayA as $keyA => $itemA) {
foreach ($arrayB as $keyB => $itemB) {
if ($keyA == $keyB) {
$outputA[$keyA] = $itemA;
$outputB[$keyB] = $itemB;
}
}
This should give you two arrays, $outputA and $outputB, which look just like $arrayA and $arrayB, except they only include key=>value pairs if the key was present in both original arrays.
foreach($arrayA as $k=>$a)
if (!isset($arrayB[$k]))
unset($arrayA[$k];
Take a look to php : array_diff
http://docs.php.net/manual/fr/function.array-diff.php

Get all array data with a certain string

I want to get all the array data where keys has the characters 'ch' from the start. How do I get it?
Array ( [editpostid] => 0 [editpostcat] => 1 [ch114] => on [ch115] => on )
The keys of the data may vary as the numbers come from the record id's from the database.
how do I place all the data with 'ch' in the start of keys on to a separate array?
Do like this
<?php
$arr = array('ch'=>10,'abch'=>20,'ch23'=>45);
$newarr=array();
foreach($arr as $k=>$v)
{
if(substr(strtolower($k),0,2)=='ch')
{
array_push($newarr,$v); // Make use of this if you just need the values
//$newarr[$k]=$v; // Uncomment this and comment above statement, if you need the keys too
}
}
print_r($newarr);
OUTPUT:
Array
(
[0] => 10
[1] => 45
)
$charray=array();
foreach($yourarray as $key=>$value){
if(preg_match("/^ch/",$key)){
$charray[$key]=>$value;
}
}
//$charray is the new arrayas you asked for
echo implode(',',$charray);
refer official documentation for preg_match for more information

Categories