using array_intersect_key on a single array - php

I have an array which looks like this:
Array
(
[0] => Array
(
[Binding] => Video Game
[Brand] => Sony
[Color] => Crystal black
[EAN] => 0151903136010
[Edition] => WiFi
)
[1] => Array(
[Binding] => Console
[Brand] => Nintendo
[Color] => blk n wht
[EAN] => 0045496880866
[Edition] => Deluxe Set
)
What I want to do is to be able to extract only the common keys, the value doesn't matter. The items in this array can range from 2 to 6.
It seems like array_intersect_key is the function that I'm looking for but it takes 2 or more arrays as an argument so I'll have to do something like:
$item_count = count($items);
if($item_count == 2){
$intersection = array_intersect_key($items[0], $items[1]);
}else if($item_count == 3){
$intersection = array_intersect_key($items[0], $items[1], $items[2]);
}
It feels like pretty tedious to do it this way. Any ideas what would be the easier and more elegant way to do this without using ifs? Thanks in advance!

Use call_user_func_array():
//$array is your original array
$result = call_user_func_array('array_intersect_key', $array);

Related

Creating a multi dimensional Array from two arrays

I have the following 2 arrays:
Array 1
(
[0] => Speed
[1] => Grade
[2] => Speed
[3] => Grade
[4] => Speed
[5] => Grade
[6] => Grade
[7] => Speed
[8] => Size
)
Array 2
(
[0] => 5200 rpm
[1] => Red
[2] => 7200 rpm
[3] => Blue
[4] => 8900 rpm
[5] => Green
[6] => Purple
[7] => 10000 rpm
[8] => Big
)
The values are matching each other. For example: Speed - 5200 rpm , Grade - Red and so forth.
I need to make the above like the following :
$collection = array(
"Speed" => array (
5200 rpm,
7200 rpm,
8900 rpm,
10000 rpm
),
"Grade" => array (
Red,
Blue,
Green,
Purple
),
"Size" => array (
Big
)
);
It needs to make an array for each label and store the necessary values into the array. I have tried merging and combining and looping. I am going wrong somewhere.
Can someone please help me out.
Try this code
$array_1 = array('Speed','Grade','Speed','Grade','Speed','Grade','Grade','Speed','Size');
$array_2 = array('5200 rpm','Red','7200 rpm','Blue','8900 rpm','Green','Purple','10000 rpm','Big');
foreach($array_1 as $key=>$elm){
$finalArray[$elm][] = $array_2[$key];
}
echo("<pre>");
print_r($finalArray);
echo("</pre>");
With foreach you can use label for create new array multi-dimensional! Is very easy.
I hope I have helped you, for any questions, please comment
Save array 1 as $description and array 2 as $value.
You need to get the array values of both arrays, using:
$description = array_values($description);
And then you can use array_combine.
$combined = array_combine($description, $value);
Related (for array values) Convert an associative array to a simple array of its values in php
PHP Docs for array_combine here.
EDIT
I read the question again and I see that index are the same for array 1 and array 2
$collection = array();
foreach (array1 as $key => $value){
$collection[$value][] = $array2[$key];
}

PHP Slicing a multidimensional array

I have the following print_r() from a multi-dimensional array (for simplicity I have not included all information in the array:
print_r()
Array (
[0] => Array (
...
)
[41] => Array (
[name] => London
[company] => nhyt6t
[top25_1] => 8.75912088
)
[42] => Array (
[name] => Manchester
[company] => gtr4rf
[top25_1] => 6.56758398
)
...
[75] => Array (
[name] => Leeds
[company] => de3wsd6
[top25_1] => 7.58675398
)
)
What I am trying to achieve is to slice the array so that I get the information from array [41] upwards into a new array.
I know I can use `array_slice()' but my following code doesn't work and I am sure it's because the array I am slicing from is multi-dimensional and I can't work out how to achieve this.
Non working code
$array = array_slice($row, 40);
Any and all feedback and advice welcomed.
You just need to check the manual on php -> array_slice()
$array = array_slice($row, 40, (count($row) - 40))
You simply forget to supply the 3rd parameter ($length) which we do as a count from the 41 nth item to up :)
Example
<?php
$result = array();
for($i=40;$i<count($row);$i++)
{
if(array_key_exists ($i,$row))
{
$result[$i] = $row[$i];
}
}
print_r($result );
?>

Right way to separate array specific values into another arrays

There is the following array in my application:
array (
[item_name_1] => GTA V
[item_quantity_1] => 4
[item_price_1] => 5990
[item_name_2] => Watch_Dogs
[item_quantity_2] => 1
[item_price_2] => 5990
)
I want to divide/split this array into two pieces like that:
array (
[item_name_1] => GTA V
[item_quantity_1] => 4
[item_price_1] => 5990
)
array (
[item_name_2] => Watch_Dogs
[item_quantity_2] => 1
[item_price_2] => 5990
)
If you didn't realized, I want to separate items suffixed by 1 and 2 – and successively – unto different matrices and I really don't see the best way to perform this. Maybe regex?
I already tried to play with explode() and implode(), but no success – I have no creativity enough to explore their best.
<?php
$src = array (
'item_name_1' => 'GTA V',
'item_quantity_1' => 4,
'item_price_1' => 5990,
'item_name_2' => 'Watch_Dogs',
'item_quantity_2' => 1,
'item_price_2' => 5990,
);
$dest = array();
foreach($src as $k => $v) {
$sfx = preg_replace('/.*?_([0-9]+)$/', '$1',$k);
$dest[$sfx][$k] = $v;
}
print_r($dest);

Where like queries on multidimensional arrays in php

Suppose I have a php array like this:
$shop = array( array("name"=>"Tom", "level"=> 1.25 ),
array("name"=>"Mike","level"=> 0.75 ),
array("name"=>"John","level"=> 1.15 )
);
I want to filter this array similar to filtering a mysql table with where conditions. Supposedly I want every array where level is higher than 1. I could iterate through and check with if statements. Are there any php solutions to this?
array_filter is what you are looking for:
$results= array_filter($shop, function($item) { return $item['level'] > 1; });
print_r($results);
Output:
Array
(
[0] => Array
(
[name] => Tom
[level] => 1.25
)
[2] => Array
(
[name] => John
[level] => 1.15
)
)

Efficiently transforming Arrays (PHP)

Edit: Thanks to #Felix Kling and #mario for pointing me towards named capture groups and PREG_SET_ORDER, I totally learned something today.
I'm curious about a better algorithm per se, though. So please just pretend that there's no preg_match() involved.
Edit 2: Abstracted question
While answering another question here, I stumbled upon the fact that my code for turning
this:
Array
(
[0] => Array (
[0] => 1
[1] => 3
)
[1] => Array (
[0] => Description text
[1] => Different Description text
)
[2] => Array (
[0] => 123.456.12
[1] => 234.567.89
)
[3] => Array (
[0] => 10.00
[1] => 10.00
)
[4] => Array (
[0] => 10.00
[1] => 30.00
)
)
into that:
Array
(
[0] => Array
(
[qty] => 1
[description] => "Description text"
[sku] => 123.456.12
[price] => 10.00
[total] => 10.00
)
…
)
is fugly:
$field_names = array('qty', 'description', 'sku', 'price', 'total');
$result_arr = array();
$num_iter = count(matches[0]);
for ($i = 0; $i < $num_iter; $i++) {
foreach ($field_names as $index => $field_name) {
$result_arr[$i][$field_name] = array_shift($input_arr[$index]);
}
}
Any suggestions for improvement?
There is one simpler way to produce the desired output.
while (count($input_arr[0])) {
$values = array_map("array_shift", & $input_arr);
$result_arr[] = array_combine($field_names, $values);
}
This won't work past PHP 5.3, as it requires forcibly passing a parameter by reference. (Avoiding any dumbing-down-the-language remarks here). But you can of course chop off the entries with a more elaborate manual loop at any time.
The real simplification for such cases is however array_combine to turn a list into an associative array.

Categories