Multi-Dimensional array, returning wrong result - php

I have a multi-dimensional array (There is more than one item in "data" but i'm just showing one for this question):
Array
(
[data] => Array
(
[0] => Array
(
[to] => Array
(
[data] => Array
(
[0] => Array
(
[name] => fake name
[id] => 668071477234
)
[1] => Array
(
[name] => fake name
[id] => 1345556711
)
)
)
[updated_time] => 2012-12-24T23:46:26+0000
[id] => 327424994013537
)
)
)
I am trying to loop thru the array and determine if the id matches a variable sent from $_REQUEST, and if it does, I only want to return the "updated_time" value of the iteration.
Here's what I have but the date is always wrong, and doesn't match the proper iteration:
foreach($userOutbox['data'] as $outbox){
foreach($outbox['to']['data'] as $user){
if($user['id'] == $_REQUEST['facebook_id']){
$last_message_date = $outbox['updated_time'];
}
}
}
It's late and my eyes and brain are not helping me. Can anyone give me any direction?

Here's the solution that worked for me, just added break 2; Thanks for your help:
foreach($userOutbox['data'] as $outbox){
foreach($outbox['to']['data'] as $user){
if($user['id'] == $_REQUEST['facebook_id']){
$last_message_date = $outbox['updated_time'];
break 2;
}
}
}

Related

Deleting complex array element

So I want to delete an array element from a JSON array based on an id in a sub-array. I know it sounds weird. Here's an example of the array. I want to delete the entire array [0] based on the [dealer][id] array where the [id] = 20220 in this example.
Array
(
[results] => Array
(
[offset] => 1
[length] => 15
[data] => Array
(
[0] => Array
(
[dealer] => Array
(
[id] => 20220
[name] => apple
)
)
)
)
}
In reality there are a lot more elements in the [results] array. I'm not sure how to go about it.
Any help is greatly appreciated!
Loop thru data key first then check if dealer id matches the searched id
$id = 20220;
foreach ($array['results']['data'] as $key => $value) {
if ($value['dealer']['id'] == $id) {
unset($array['results']['data'][$key]);
}
}
use array_filter,
$array['results']['data'] = array_filter($array['results']['data'], function($v){return $v['dealer']['id'] != 20220;});

merging array in CI 3

I want to merge two arrays in order to get the data as per my requirement.
I am posting my result, please have a look.
First array:
Array
(
[0] => Array
(
[km_range] => 300
[id] => 2
[car_id] => 14782
)
[1] => Array
(
[km_range] => 100
[id] => 3
[car_id] => 14781
)
[2] => Array
(
[km_range] => 300
[id] => 4
[car_id] => 14783
)
)
Second array:
Array
(
[0] => Array
(
[user_id] => 9c2e00508cb28eeb1023ef774b122e86
[car_id] => 14783
[status] => favourite
)
)
I want to merge the second array into the first one, where the value at key car_id matches the equivalent value; otherwise it will return that field as null.
Required output:
<pre>Array
(
[0] => Array
(
[km_range] => 300
[id] => 2
[car_id] => 14782
)
[1] => Array
(
[km_range] => 100
[id] => 3
[car_id] => 14781
)
[2] => Array
(
[km_range] => 300
[id] => 4
[car_id] => 14783
[fav_status] => favourite
)
)
Since the merge is so specific I would try something like this:
foreach ($array1 as $index => $a1):
foreach ($array2 as $a2):
if ($a1['car_id'] == $a2['car_id']):
if ($a2['status'] == "favourite"):
$array1[$index]['fav_status'] = "favourite";
endif;
endif;
endforeach;
endforeach;
You might be able to optimize the code more but this should be very easy to follow...
Another way to achieve this without using the index syntax is to reference the array elements in the foreach by-reference by prepending the ampersand operator:
foreach($firstArray as &$nestedArray1) {
foreach($secondArray as $nestedArray2) {
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1['fav_status'] = $nestedArray2['status'];
}
}
}
You can see it in action in this Playground example.
Technically you asked about merging the arrays. While the keys would be different between the input arrays and the desired output (i.e. "status" vs "fav_status"), array_merge() can be used to merge the arrays.
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1 = array_merge($nestedArray1, $nestedArray2);
}
Playground example.
Additionally the union operators (i.e. +, +=) can be used.
If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator1
if ($nestedArray1['car_id'] == $nestedArray2['car_id']) {
$nestedArray1 += nestedArray1;
}
Playground example.
1http://php.net/manual/en/function.array-merge.php#example-5587

PHP Nested foreach with Key

I have been trying to work this out for two days now and am hitting a brick wall. I have a skyscanner array that has flight itineraries where I have the flight
Leg - being Itineraries -> OutboundLegId -
and also the legs which shows the flight number - being
Legs -> FlightNumbers -> FlightNumber.
What I am trying to achieve is to display the Itinerary and then join the Flight Number on to that. But no matter what I try I cannot get this to work. I have read all about Keys on here and tried loads of examples but am coming up with nothing. Can someone point me in the right direction please?
Example arrays below
[Itineraries] => Array
(
[0] => Array
(
[OutboundLegId] => 13542-1610140610-29-0-13445-1610141240
[InboundLegId] => 13445-1610211340-29-0-13542-1610211640
[PricingOptions] => Array
(
[0] => Array
(
[Agents] => Array
(
[0] => 2174187
)
[QuoteAgeInMinutes] => 31
[Price] => 200.98
[DeeplinkUrl] => http://partners.api.skyscanner.net/apiservices/deeplink/v2?_cje=5JlLCgyPUKY0hT8T0Ybh6dL0Xf0htAiHTFX7RU79eeI3XvrsxvEqP1QUJAoHiHRd&url=http%3a%2f%2fwww.apideeplink.com%2ftransport_deeplink%2f4.0%2fUK%2fen-gb%2fGBP%2fcook%2f2%2f13542.13445.2016-10-14%2c13445.13542.2016-10-21%2fair%2fairli%2fflights%3fitinerary%3dflight%7c-32294%7c1152%7c13542%7c2016-10-14T06%3a10%7c13445%7c2016-10-14T12%3a40%2cflight%7c-32294%7c1153%7c13445%7c2016-10-21T13%3a40%7c13542%7c2016-10-21T16%3a40%26carriers%3d-32294%26passengers%3d1%2c0%2c0%26channel%3ddataapi%26cabin_class%3deconomy%26facilitated%3dfalse%26ticket_price%3d200.98%26is_npt%3dfalse%26is_multipart%3dfalse%26client_id%3dskyscanner_b2b%26request_id%3d3bc96bda-fd7c-403a-b841-2ccc3c26071d%26commercial_filters%3dfalse%26q_datetime_utc%3d2016-09-29T08%3a18%3a27
)
[Legs] => Array
(
[0] => Array
(
[Id] => 13542-1610140610-29-0-13445-1610141240
[SegmentIds] => Array
(
[0] => 1
)
[OriginStation] => 13542
[DestinationStation] => 13445
[Departure] => 2016-10-14T06:10:00
[Arrival] => 2016-10-14T12:40:00
[Duration] => 270
[JourneyMode] => Flight
[Stops] => Array
(
)
[Carriers] => Array
(
[0] => 105
)
[OperatingCarriers] => Array
(
[0] => 105
)
[Directionality] => Outbound
[FlightNumbers] => Array
(
[0] => Array
(
[FlightNumber] => 1152
[CarrierId] => 105
)
)
)
Assuming this is one big array and its called $data you can nest a couple of foreach loops.
I use foreach loops as I assume there are cases where this data structure get more complex than the one you show
foreach ( $data['Itineraries'] as $itin ) {
foreach ( $data['Legs'] as $legs) {
if ($legs['Id'] == $itin['OutboundLegId']) {
// we matched the itinerary with a leg
echo $legs['OutboundLegId'] . ' ' . $legs['FlightNumbers'][0]['FlightNumber'];
}
}
}
Use it as draft. Can't perform function without feedback.
Put proper arrays instead of {YOUR-ARRAY-WITH-LEGS} and {YOUR-ARRAY-WITH-ITINERARIES}
$sortedLegs = array_column('Id', {YOUR-ARRAY-WITH-LEGS});
$joinedArray = array_map(function($itinerary) use($sortedLegs){
if(array_key_exists($itinerary['OutboundLegId'],$sortedLegs)) {
$itinerary['legs'] = $sortedLegs[$itinerary['OutboundLegId']];
}
return $itinerary;
},{YOUR-ARRAY-WITH-ITINERARIES});

PHP array_push() - pushing new data to array

I have an array which looks like this:
Array
(
[0] => Array
(
[1] => Array
(
[name] => vrij
// ...
)
[2] => Array
(
[name] => zat
// ...
)
)
)
I build this array using a for loop; however, I need to push 4 more 'records' to the array, which I can't do in this for loop.
I want the array to look like this, after the pushes:
Array
(
[0] => Array
(
[1] => Array
(
[name] => vrij
// ...
)
[2] => Array
(
[name] => zat
// ...
)
// ...
)
[1] => Array
(
[1] => Array
(
[name] => zon
//...
)
[2] // etc
)
)
The four new records should be pushed to array[1], so I get something like
$array[1][0], $array[1][1], etc. 0 1 2 3 contains the new data.
I tried quite a lot of stuff, to be honest. I need to do four of these pushes, so I was trying a for loop:
for($i = 0; $i < 4; $i++)
{
$day_info = $this->get_day_info($i, $data['init']['next_month'], $data['init']['current_year']);
$push['name'] = $day_info['day_name'];
array_push($data['dates'], $push);
}
and all other kinds of things with [], [1][$i], etc. Sometimes it even adds five arrays! I'm confused as to why it won't just add the [1][1], [1][2],.. I'm probably missing out on something here. Thanks a lot.
If this isn't clear, please do tell and I'll add more code to explain the problem better.
$extradates = array(1 => 'zon', 2 => 'maa');
$data['dates'][] = $extradates;
Will add 2 extra dates to the array using a new index.
Although if I see what you trying to accomplish, I think there might be a better way.
This above works though :)

Formating a single result in php multidimensional to match?

I'm grabbing a some XML data and parsing it with PHP.
Most of the results come in multidimensional array but occasionally I'll get a result in a single array and it breaks my script.
I'm trying to format the single result to match the format of the results in the multidiminsonal array but I'm not having any luck.
Here is what I got:
Array
(
[name] => Steve Jobs
[id] => 3
)
Array
(
[0] => Array
(
[name] => Steve Jobs
[id] => 6
)
[1] => Array
(
[name] => Bill Gates
[id] => 8
)
)
I'm trying to format the single result to match the multidimensional format then flatten...
Array
(
[0] => Array
(
[name] => Steve Jobs
[id] => 3
)
[1] => Array
(
[name] => Steve Jobs
[id] => 6
)
[2] => Array
(
[name] => Bill Gates
[id] => 8
)
)
I've tried this:
$array_check = #array_keys($result[0]['name']);
if ($array_check[0] == "0") {
$result;
} elseif ($array_check[0] == "name") {
$ReWrite = array ([0] =>
array (['name']=>
array ($result[0]['name'])
));
$result = $ReWrite;
}
I thought that would do it but it's off...
Try this:
$array_check = #array_keys($result[0]['name']);
if (!isset($array_check[0])) {
$result[] = $array_check;
} else {
$result = $array_check;
}
var_dump($result);
If your first array was assigned to the variable $singleArray and your target results stored in $results, try this array_push($results, $singleArray);
Use this together with reset() it returns the first element of an array:
if(!is_array(reset($result))){
array_push($results, $result);
}
This will test if the array does not contain an array as an element, if it doesn't push the whole array to an aggregate array.
Edit: Try this loop:
for($i = 0; $i <= count($multi); $i++){
$arr = $multi[$i];
if(!is_array($arr)){
$multi[$i] = array($arr);
}
} var_dump($multi);

Categories