PHP Slicing a multidimensional array - php

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

Related

PHP how to flatten out this indexed array?

I have the following array:
Array
(
[0] => Array
(
[ContractorName] => Joe Soap
[BonusAmount] => 73.92
)
[1] => Array
(
[ContractorName] => Mike Michaels
[BonusAmount] => 68.55
)
[2] => Array
(
[ContractorName] => John Smith
[BonusAmount] => 34.35
)
[3] => Array
(
[ContractorName] => Pete Peterson
[BonusAmount] => 24.61
)
[4] => Array
(
[ContractorName] => Pete Smith
[BonusAmount] => 22.76
)
)
How do I go about ending up with an array that looks like this:
Array
(
[Joe Soap] => 73.92
[Mike Michaels] => 68.55
[John Smith] => 34.35
[Pete Peterson] => 24.61
[Pete Smith] => 22.76
)
I'm a bit lost at the moment. I have tried creating a new array by looping over the first array, but I'm getting unwanted results. Any help greatly appreciated.
Use array_combine with array_column as
array_combine(array_column($records, 'ContractorName'),array_column($records, 'BonusAmount'));
Go through entire array using foreach and then use each piece to construct new array.
$out = [];
foreach ($inputArray as $v) {
$out[$v['ContractorName']] = $v['BonusAmount'];
}
Second solution is by using array_combine and array_column.
$keys = array_column($inputArray, 'ContractorName');
$values = array_column($inputArray, 'BonusAmount');
$output = array_combine($keys, $values);
//Or put everything in single line
$output = array_combine(array_column($inputArray, 'ContractorName'), array_column($inputArray, 'BonusAmount'));
Third option
$output = array_column($inputArray, 'BonusAmount', 'ContractorName');
You can use one array_column(), and with the third parameter to specify the index. Live Demo.
array_column($array, 'BonusAmount', 'ContractorName');

Iterate through multidimensional PHP array and output values

I'm having a real headache trying to iterate through an array and output elements. Using the array structure below I want to be able to output each instance of partname.
The following loop outputs the first instance of partname. I can't seem to adapt it to loop through all instances within the array. I'm sure I'm missing something basic.
foreach($ItemsArray['assignments'] as $item) {
$partname = $item['grades'][0]['partname'];
}
Array
(
[assignments] => Array
(
[0] => Array
(
[assigntmentid] => 5101
[grades] => Array
(
[0] => Array
(
[id] => 5101
[name] => Advanced AutoCad
[partid] => 6601
[partname] => Draft
[userid] => 82069
[grade] => 53
[courseid] => 6265
[fullname] => Computer Aided Design
)
)
)
[1] => Array
(
[assigntmentid] => 5101
[grades] => Array
(
[0] => Array
(
[id] => 5101
[name] => Advanced AutoCad
[partid] => 6602
[partname] => Final
[userid] => 82069
[grade] => 35
[courseid] => 6265
[fullname] => Computer Aided Design
)
)
)
)
)
Instead of just coding by slapping the keyboard. Write down what your function needs to do. In english (or whatever language you prefer). This would be something like:
Foreach assignment, loop over all grades and store the partname of
that grade into an array.
And then code it:
function getPartnames($assignments) {
$partNames = array();
foreach ($assignments as $assignment) {
foreach($assignment['grades'] as $grade) {
$partNames[] = $grade['partname'];
}
}
return $partNames;
}
So what did I do? I simply translated english to code.
Some few more tips: Use variables names that make sense. $item; $ItemArray; ... don't make sense. They tell me nothing
use an extra foreach in your loop:
foreach($ItemsArray['assignments'] as $item) {
foreach($item['grades'] as $grade) {
echo $grade['partname'];
}
}

How to set new index in previous array using for each loop

here is my code
array 1:
Array
(
[0] => Array
(
[id] => 42166
[Company_Website] => http://www.amphenol-highspeed.com/
[company_name] => Amphenol High Speed Interconnect
[city_name] => New York
[country_name] => USA
[comp_img] =>
)
)
array 2:
Array
(
[0] => Array
(
[Product_Name] => CX to CX,Amphenol High Speed Active,Serial Attached SCSI
[company_id] => 42166
)
)
php code:
$total = count($result);
$i=0;
foreach ($result as $key=>$value) {
$i++;
$company_id= implode(",",(array)$value['id']);
if ($i != $total)
echo',';
}
code to fetch array 2:
foreach ($res as $key1=>$value1) {
echo $total;
$event[$value['company_name']] = $value1['Product_Name'];
if($value1['company_id']==$company_id )
{
echo " match";
//$key[['company_name']]= $value1['Product_Name'];
}
else
{
echo "not matched";
}
}
what i need create a new index if company_id is match with id of another array.
that is product_name.
if product name is there just create index otherwise show null.
i want show in key=> value .
output should be like:
Array
(
[0] => Array
(
[id] => 42166
[Company_Website] => http://www.amphenol-highspeed.com/
[company_name] => Amphenol High Speed Interconnect
[city_name] => New York
[country_name] => USA
[comp_img] =>
[Product_Name] => CX to CX,Amphenol High Speed Active,Serial Attached SCSI
)
)
Your all problems with keys in arrays will disappear when you will start using company ids as a keys.
To reindex you arrays, you can use:
$array1 = array_combine(array_column($array1, 'id'), $array1);
$array2 = array_combine(array_column($array2, 'company_id'), $array2);
In the output you will get:
array 1:
Array
(
[42166] => Array
(
[id] => 42166
...
)
)
And array 2 will looks similiar - id as a key.
So accessing to the elements using ids as a keys is a piece of cake right now.

using array_intersect_key on a single array

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

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

Categories