PHP Getting Values From Nested Array - php

I am trying to get the 'name' value from within a 'nested array' I am not sure if thats the correct term in PHP.
Array (
[0] => Array
(
[event] => Array
(
[id] => 28140972
[name] => Northwich v Lincoln United FC
[countryCode] => GB
[timezone] => Europe/London
[openDate] => 2017-03-08T19:45:00.000Z
)
[marketCount] => 24
)
[1] => Array
(
[event] => Array
(
[id] => 28140974
[name] => Viimsi MRJK v Paide Linnameeskond II
[countryCode] => EE
[timezone] => Europe/London
[openDate] => 2017-03-08T17:00:00.000Z
)
[marketCount] => 24
)
}
I am trying to access the 'name' key of every item in the array, but struggling to do it. Any advice?

$arrayOfNames = array_map(function ($item) {
return $item['event']['name'];
}, $yourPreviousArray);
Test case:
>>> print_r($data)
Array
(
[0] => Array
(
[event] => Array
(
[id] => 1
[name] => James
)
)
[1] => Array
(
[event] => Array
(
[id] => 2
[name] => Jim
)
)
)
=> true
>>> array_map(function($item) {
... return $item['event']['name'];
... }, $data)
=> [
"James",
"Jim",
]
>>>

You can do something like this:
foreach ($array as $item) {
echo $item['event']['name'].'<br/>';
}

Related

Merge subarrays of multidimensional array based on sub value

I have a multidimensional array like this, I need to merge subarrays with the same messageID value.
$myarray = Array (
[0] => Array
(
[messageId] => 5ACE9D8841
[sender] => john#doe.com
)
[1] => Array
(
[messageId] => 7EE67D8170
[sender] => dan#doe.com
)
[2] => Array
(
[messageId] => 8095FD8836
[sender] => cat#doe.com
)
[3] => Array
(
[messageId] => 7EE67D8170
[dest] => mitch#doe.com
[status] => sent
[date] => 2021-02-01 11:06:55
)
);
Expected result , [1] and [3] are merged into [1] because they share the same [messageId] :
Array
(
[0] => Array
(
[messageId] => 5ACE9D8841
[sender] => john#doe.com
)
[1] => Array
(
[messageId] => 7EE67D8170
[dest] => mitch#doe.com
[status] => sent
[date] => 2021-02-01 11:06:55
[sender] => dan#doe.com
)
[2] => Array
(
[messageId] => 8095FD8836
[sender] => cat#doe.com
)
)
I don't mind about the key index or the order.
EDIT : I've tried array_merge, array_merge_recursive and many others. Best result was obtained with
foreach ($myarray as $sub_arr) {
$result_arr = array_merge($result_arr, $sub_arr);
$result_arr = array_unique($result_arr);
}
It works but returns only the last iteration :
Array
(
[messageId] => 7EE67D8170
[dest] => mitch#doe.com
[status] => sent
[date] => 2021-02-01 11:06:55
[sender] => dan#doe.com
)
Regards
Try using array_reduce function with callback function:
$result = array_values(array_reduce($myarray, function($rows, $item){
if (array_key_exists('messageId', $item) && is_scalar($item['messageId'])) {
$rows = array_replace_recursive($rows ?? [], [$item['messageId'] => $item]);
}
return $rows;
}));
print_r($result);
fiddle

Merging two array elements in one

How can I do to merge "artist" value with "title" value in one value?. I'm using PHP 5.2.4 if that helps.
I have this array
Array
(
[0] => Array
(
[artist] => Narcosis
[title] => Destruir
[duration] => 137
[date] => 1370807642
[genre_id] => 18
)
[1] => Array
(
[artist] => Ricardo Palma Fanjul
[title] => Mutant
[duration] => 347
[date] => 1448227909
[genre_id] => 18
)
)
The expected output would be like this, just show element "title" with twice values:
Array
(
[0] => Array
(
[title] => Narcosis - Destruir
[duration] => 137
[date] => 1370807642
[genre_id] => 18
)
[1] => Array
(
[title] => Ricardo Palma Fanjul - Mutant
[duration] => 347
[date] => 1448227909
[genre_id] => 18
)
)
Try this:
foreach ($mainArr as $index=>$subArr) {
$subArr['title'] = $subArr['artist'].' - '.$subArr['title'];
unset($subArr['artist']);
$mainArr[$index] = $subArr;
}
mainArr is the array declared above.
p.s. I have not tested this code yet
Try this:
$new = array_map(function($v) {
$v['title'] = $v['artist'].' - '.$v['title'];
unset($v['artist']);
return $v;
}, $arr);
OR
foreach ($arr as &$a) {
$a['title'] = $a['artist'].' - '.$a['title'];
unset($a['artist']);
}

PHP Looping multi dim array

Array
(
[stat] => ok
[offset] => 0
[limit] => 50
[total] => 1
[monitors] => Array
(
[monitor] => Array
(
[0] => Array
(
[id] =>
[friendlyname] =>
[url] =>
[type] => 3
[subtype] =>
[keywordtype] =>
[keywordvalue] =>
[httpusername] =>
[httppassword] =>
[port] =>
[interval] => 300
[status] => 2
[alltimeuptimeratio] => 100
[log] => Array
(
[0] => Array
(
[type] => 2
[datetime] => 11/24/2016 04:01:32
)
[responsetime] => Array
(
[0] => Array
(
[datetime] => 12/09/2016 19:34:02
[value] => 109
)
[1] => Array
(
[datetime] => 12/09/2016 19:29:02
[value] => 110
)
[2] => Array
(
[datetime] => 12/09/2016 19:24:02
[value] => 110
)
)
)
)
)
)
I need to get the value of datetime, and value from the responsetime array. I tried the following but it seems to not return anything.
foreach($multidim as $value) {
foreach($value as $key => $val) {
if($key == "responsetime") {
echo $val[3];
}
}
}
Where $multidim is the large multi-dim array listed above. Any help is appreciated as I am not sure where to go from here.
Thank you in advance.
to access all the response times you should do sth like this
foreach($multidim['monitors']['monitor'][0]['responsetime'] as $key => $value) {
//here $key will be 0,1,2,3...
//$value['datetime'] will be 11/24/2016 04:01:32...
//$value['value'] will be 109,110,...
}
that is if you just want to access all the response times of the first monitor. if you want to access all the monitors and their response times you would need 2 loops for example
foreach($multidim['monitors']['monitor'] as $monitorId => $monitorData) {
foreach($monitorData['responsetime'] as $key => $value) {
//here you can access all the variables e.g
//$monitorId will be 0,1,2,3...
//$key will be 0,1,2,3...
//$value['datetime'] will be 11/24/2016 04:01:32...
//$value['value'] will be 109,110,...
}
}
I hope that sends you in the right direction :)

How to extract parts of this array - PHP

I am trying to print part of this array, basically all the URLS [href] with "ProviderRedirect.ashx" basically [0] to [infinite]
Array
(
[name] => HC Redirect
[count] => 66
[frequency] => Daily
[version] => 14
[newdata] => 1
[lastrunstatus] => partial
[thisversionstatus] => success
[nextrun] => Sun Jan 17 2016 14:03:08 GMT+0000 (UTC)
[thisversionrun] => Sat Jan 16 2016 14:03:08 GMT+0000 (UTC)
[results] => Array
(
[collection1] => Array
(
[0] => Array
(
[Hotel Search] => Array
(
[href] => https://www.domain.com/ProviderRedirect.ashx?key=0.6359329.272723160.5179.GBP.1729297590&saving=410&source=32-0
[text] => View Deal
)
[index] => 1
[url] => https://www.domain.com/Hotels/Search?destination=place:London&checkin=2016-09-02&checkout=2016-09-09&Rooms=1&adults_1=2&languageCode=EN¤cyCode=GBP&pageSize=50
)
[1] => Array
(
[Hotel Search] => Array
(
[href] => https://www.domain.com/ProviderRedirect.ashx?key=0.21199849.272723130.457.GBP.753573779&source=32-0
[text] => View Deal
)
[index] => 2
[url] => https://www.domain.com/Hotels/Search?destination=place:London&checkin=2016-09-02&checkout=2016-09-09&Rooms=1&adults_1=2&languageCode=EN¤cyCode=GBP&pageSize=50
)
[2] => Array
(
[Hotel Search] => Array
(
[href] => https://www.domain.com/ProviderRedirect.ashx?key=0.23906211.272723157.1326.GBP.2008823249&source=32-0
[text] => View Deal
)
[index] => 3
[url] => https://www.domain.com/Hotels/Search?destination=place:London&checkin=2016-09-02&checkout=2016-09-09&Rooms=1&adults_1=2&languageCode=EN¤cyCode=GBP&pageSize=50
)
[3] => Array
(
[Hotel Search] => Array
(
[href] => https://www.domain.com/ProviderRedirect.ashx?key=0.5242811.272723157.3854.GBP.1642352834&source=32-0
[text] => View Deal
)
[index] => 4
[url] => https://www.domain.com/Hotels/Search?destination=place:London&checkin=2016-09-02&checkout=2016-09-09&Rooms=1&adults_1=2&languageCode=EN¤cyCode=GBP&pageSize=50
)
[4] => Array
(
[Hotel Search] => Array
(
[href] => https://www.domain.com/ProviderRedirect.ashx?key=0.675524.272723160.1457.GBP.2121712597&saving=18&source=32-0
[text] => View Deal
)
[index] => 5
[url] => https://www.domain.com/Hotels/Search?destination=place:London&checkin=2016-09-02&checkout=2016-09-09&Rooms=1&adults_1=2&languageCode=EN¤cyCode=GBP&pageSize=50
)
[5] => Array
(
[Hotel Search] => Array
(
[href] => https://www.domain.com/ProviderRedirect.ashx?key=0.5743724.272723155.847.GBP.1001086600&source=32-0
[text] => View Deal
)
[index] => 6
[url] => https://www.domain.com/Hotels/Search?destination=place:London&checkin=2016-09-02&checkout=2016-09-09&Rooms=1&adults_1=2&languageCode=EN¤cyCode=GBP&pageSize=50
)
[6] => Array
Either use array_walk_recursive() function or write your own function to recursively traverse the array and print all urls.
Suppose $arr is your array.
Method(1):
array_walk_recursive($arr, function($item, $key) {
if ($key == "href") {
echo $item . "<br />";
}
});
Method(2):
function process_array($array){
foreach($array as $key => $value){
if(is_array($value)){
process_array($value);
}else{
if($key == "href"){
echo $value . "<br />";
}
}
}
}
process_array($arr);
$items = array(
'results' => array(
'collection1'=> array(
array(
'hotel_search'=>array(
'href'=>'value'
),
'index'=>'value'
),
array(
'hotel_search'=>array(
'href'=>'value'
),
'index'=>'value'
)
)
)
);
$collection1 = $items['results']['collection1'];
foreach($collection1 as $collection) {
printf("%s", $collection['hotel_search']['href']);
}
You would need to loop over the results array though to avoid hardcoding
If all you need to do is print the values, array_walk_recursive would do the job:
array_walk_recursive($array, function($item, $key) {
if ('href' === $key) {
echo "$item\n";
}
});

how to merge key array on array

and i got a problem (its big for me) :(
ok, i have some array like ...
Array(
[0] => Array
(
[id] => 1
[order_sn] => EU/2011/04/PO/5
[total] => 65
)
[1] => Array
(
[id] => 1
[order_sn] => EU/2011/04/RS/4
[total] => 230
)
[2] => Array
(
[id] => 1
[order_sn] => EU/2011/04/RS/3
[total] => 130
)
[3] => Array
(
[id] => 2
[order_sn] => EU/2011/04/RS/2
[total] => 100
)
[4] => Array
(
[id] => 2
[order_sn] => EU/2011/04/RS/1
[total] => 60
)
)
how to merge them if the array have same key value ... ?
the result that i need got is like this ...
Array(
[0] => Array
(
[id] => 1
[detail] => Array
(
[0] => Array
(
[order_sn] => EU/2011/04/PO/5
[total] => 65
)
[1] => Array
(
[order_sn] => EU/2011/04/RS/4
[total] => 230
)
[2] => Array
(
[order_sn] => EU/2011/04/RS/3
[total] => 130
)
)
)
[2] => Array
(
[id] => 2
[detail] => Array
(
[0] => Array
(
[order_sn] => EU/2011/04/RS/2
[total] => 100
)
[1] => Array
(
[order_sn] => EU/2011/04/RS/1
[total] => 60
)
)
)
)
im very need some help here, and im working on PHP ... what method should i do for this case?
i try too searching on google and in here ... but i dont know the keyword >.<
Many thanks before :)
regard, Stecy
Try like this:
<?php
$result = array();
foreach ($my_array as $v) {
$id = $v['id'];
$result[$id]['id'] = $id;
$result[$id]['detail'][] = array(
'order_sn' => $v['order_sn'],
'total' => $v['total'],
);
}
You can just loop over the array and build a resulting one:
// $a is your array
$r=array();
foreach($a as $v)
$r[$v['id']][]=array('order_sn'=>$v['order_sn'], 'total'=>$v['total']);
echo'<pre>';
var_dump($r);
Since you do the paring by ID, it is wise to have it as the key and all the data associated with it as the value. There's no need to also have id and detail.
foreach($origianlArray as $key => $value){
$newArray[$value['id']]['id'] = $value['id'];
$newArray[$value['id']]['detail'][] = array('order_sn' => $value['order_sn'], 'total' => $value['total']);
}
Check out the PHP array_merge function.

Categories