PHP Mutli-Dimensional Array Grabbing Item - php

I have an API which I'm trying to get an ID from, but the output is a mutli-dimensional array and I can't grab just the ID.
This is what the array looks like:
Array ( [{ data] => [ { account_key [ is_owner] => true [ id] => 1 [ name] => test [ display_name] => test [ balance] => 0 [ paid_to_date] => 0 [ updated_at] => 1577724986 [ archived_at] => null [ address1] => [ address2] => [ city] => [ state] => [ postal_code] => [ country_id] => 0 [ work_phone] => [ private_notes] => [ public_notes] => [ last_login] => [ website] => [ industry_id] => 0 [ size_id] => 0 [ is_deleted] => false [ payment_terms] => 30 [ vat_number] => [ id_number] => [ language_id] => 0 [ currency_id] => 0 [ custom_value1] => [ custom_value2] => [ invoice_number_counter] => 1 [ quote_number_counter] => 1 [ task_rate] => 0 [ shipping_address1] => [ shipping_address2] => [ shipping_city] => [ shipping_state] => [ shipping_postal_code] => [ shipping_country_id] => 0 [ show_tasks_in_portal] => true [ send_reminders] => true [ credit_number_counter] => 1 [ custom_messages] => {} [ contacts] => [ { account_key [ is_owner] => true [ id] => 1 [ first_name] => test [ last_name] => test [ email] => me#idontlikespam.com [ contact_key] => mq1dzpkqznfgtqwhdwt9nte1ohmvsju1 [ updated_at] => 1577724986 [ archived_at] => null [ is_primary] => true [ phone] => [ last_login] => [ send_invoice] => true [ custom_value1] => [ custom_value2] => } ] } ] [ meta] => { pagination [ count] => 1 [ per_page] => 15 [ current_page] => 1 [ total_pages] => 1 [ links] => [] } } } )
This is the code I have so far to split it out:
$clients = str_replace('"', "", $clients);
$convert_to_array = explode(',', $clients);
for($i=0; $i < count($convert_to_array ); $i++){
$key_value = explode(':', $convert_to_array [$i]);
$end_array[$key_value [0]] = $key_value [1];
}
print_r($end_array);
foreach ($end_array as $key => $item)
{
echo "[" . $key . "] => " . $item . "<br />";
if ($key = ' id')
{
echo $item;
}
}
It's just the final step I'm missing, it's probably something easy, but I'm still running on a Christmas brain...
New data:
stdClass Object ( [data] => Array ( [0] => stdClass Object ( [account_key] => jvg7qgtw2btrlmpigrq2zpco48eegxvv [is_owner] => 1 [id] => 1 [name] => test [display_name] => test [balance] => 0 [paid_to_date] => 0 [updated_at] => 1577724986 [archived_at] => [address1] => [address2] => [city] => [state] => [postal_code] => [country_id] => 0 [work_phone] => [private_notes] => [public_notes] => [last_login] => [website] => [industry_id] => 0 [size_id] => 0 [is_deleted] => [payment_terms] => 30 [vat_number] => [id_number] => [language_id] => 0 [currency_id] => 0 [custom_value1] => [custom_value2] => [invoice_number_counter] => 1 [quote_number_counter] => 1 [task_rate] => 0 [shipping_address1] => [shipping_address2] => [shipping_city] => [shipping_state] => [shipping_postal_code] => [shipping_country_id] => 0 [show_tasks_in_portal] => 1 [send_reminders] => 1 [credit_number_counter] => 1 [custom_messages] => {} [contacts] => Array ( [0] => stdClass Object ( [account_key] => jvg7qgtw2btrlmpigrq2zpco48eegxvv [is_owner] => 1 [id] => 1 [first_name] => test [last_name] => test [email] => ema#il.co.uk [contact_key] => mq1dzpkqznfgtqwhdwt9nte1ohmvsju1 [updated_at] => 1577724986 [archived_at] => [is_primary] => 1 [phone] => [last_login] => [send_invoice] => 1 [custom_value1] => [custom_value2] => ) ) ) ) [meta] => stdClass Object ( [pagination] => stdClass Object ( [total] => 1 [count] => 1 [per_page] => 15 [current_page] => 1 [total_pages] => 1 [links] => Array ( ) ) ) )

In Array you can access to values by [index].
In stdObject you can access to properties by -> because it is object.
So
stdClass Object ( [data] => Array ( [0] => stdClass Object ( [account_key]
Is
Object->(property data has value array)[index 0 in array and is object]->(property account_key)
On your data you need this.
foreach ($end_array->data as $key => $item)
{
echo $item->id . "<br />";
}
or if you know if data can have always one item you can access with this shortcut
echo $end_array->data[0]->id;

Related

Create PHP stdClass object from array

I am trying to create this format of information/Array in PHP
[OverrideEmailSettings] => stdClass Object (
[email#domain.com] => stdClass Object (
[Reports] => Array (
[0] => stdClass Object (
[ReportType] => 1
[SummaryFrequency] => Array (
[0] => stdClass Object (
[FrequencyType] => 8011
[SecondsPast] => 32400
)
)
[Filter] => stdClass Object (
[ClauseType] => and
[RuleField] =>
[RuleOperator] =>
[RuleValue] =>
[ClauseChildren] => Array (
[0] => stdClass Object (
[ClauseType] =>
[RuleField] => BackupJobDetail.TimeSinceStarted
[RuleOperator] => int_lte
[RuleValue] => 86400
)
)
)
)
)
)
)
Here is my code - $line = the equivelent to email#domain.com
$x = array(
'Reports' => array(
'ReportType' => '1',
'SummaryFrequency' => array(
'FrequencyType' => '8011',
'SecondsPast' => '32400',
),
'Filter' => array(
'ClauseType' => 'or',
'RuleField' => '',
'RuleOperator' => '',
'RuleValue' => '',
'ClauseChildren' => array(
'ClauseType' => '',
'RuleField' => 'BackupJobDetail.TimeSinceStarted',
'RuleOperator' => 'int_lte',
'RuleValue' => '86400',
),
),
),
);
$account_get_user_profile->OverrideEmailSettings->$line = $x;
But I think I have formatted it incorrectly.
You need to cast your arrays to stdClass like:
<?php
$x = [
"Reports" => [
(object) [
"ReportType" => "1",
"SummaryFrequency" => [
(object) [
"FrequencyType" => "8011",
"SecondsPast" => "32400",
],
],
"Filter" => (object) [
"ClauseType" => "or",
"RuleField" => "",
"RuleOperator" => "",
"RuleValue" => "",
"ClauseChildren" => [
(object) [
"ClauseType" => "",
"RuleField" => "BackupJobDetail.TimeSinceStarted",
"RuleOperator" => "int_lte",
"RuleValue" => "86400",
],
],
],
],
],
];
print_r($x);
Look PHP online code

Change key array based other array

The first array has the same keys as those in the sheet key content in the second array.
I would need to edit the key element of the first array, with the contents that I have in the key table in the second array, according to the keysheet
I tried in countless ways but without success, here is an illustrative image
the first:
Array
(
[0] => Array
(
[CIDADES] => PONTA GROSSA
[PERIODO] => 12:00 - 18:00
[ID] => Z8932
[END] => AV VSC DE MAUA,, ALT
[CONTRATO] => 7947488
[AREA] => AR01
[ASSINANTE] => DAVI
[BAIRRO] => OFICINAS
[OBS] => [Agendamento par]
[TEL RES] => 42410435
[TEL COM] =>
)
[1] => Array
(
[CIDADES] => PONTA GROSSA
[PERIODO] => 08:00 - 12:00
[ID] => Z7526
[END] => R P1000, FD
[CONTRATO] => 799644
[AREA] => AR01
[ASSINANTE] => BEATRIZ
[BAIRRO] => NEVES
[OBS] => [Agendamento]
[TEL RES] => 42988674761
[TEL COM] =>
)
[2] => Array
(
[CIDADES] => PONTA GROSSA
[PERIODO] => 08:00 - 12:00
[ID] => Z0979
[END] => R J93, FD
[CONTRATO] => 79490
[AREA] => AR01
[ASSINANTE] =>FERNANDES REIS
[BAIRRO] => UVARANAS
[OBS] => [Agendamentoente]
[TEL RES] => 4289986
[TEL COM] =>
)
)
And the second
Array
(
[0] => Array
(
[id] => 1
[table] => id_operacao
[sheet] => CIDADES
)
[1] => Array
(
[id] => 2
[table] => horario
[sheet] => PERIODO
)
[2] => Array
(
[id] => 3
[table] => tipo_wo
[sheet] => TIPO DE SERVICO
)
[3] => Array
(
[id] => 4
[table] => tecnico_id
[sheet] => ID
)
[4] => Array
(
[id] => 5
[table] => contrato
[sheet] => CONTRATO
)
[5] => Array
(
[id] => 6
[table] => roteamento
[sheet] => AREA
)
[6] => Array
(
[id] => 7
[table] => endereco
[sheet] => END
)
[7] => Array
(
[id] => 8
[table] => nome_cliente
[sheet] => ASSINANTE
)
[8] => Array
(
[id] => 9
[table] => bairro
[sheet] => BAIRRO
)
[9] => Array
(
[id] => 10
[table] => obs1
[sheet] => OBS
)
[10] => Array
(
[id] => 11
[table] => telefone
[sheet] => TEL RES
)
[11] => Array
(
[id] => 12
[table] => celular
[sheet] => TEL COM
)
)
Hey man I skipped a few items in the array but hopefully I got the structure right ;)
$firstArray = [
[
'CIDADES' => 'PONTA GROSSA',
'PERIODO' => '12:00 - 18:00',
'ID' => 'Z8932',
'END' => 'AV VSC DE MAUA,, ALT',
'CONTRATO' => '7947488',
'AREA' => 'AR01',
'ASSINANTE' => 'DAVI',
'BAIRRO' => 'OFICINAS',
'OBS' => ['Agendamento par'],
'TEL RES' => '42410435',
],
[
'CIDADES' => 'PONTA GROSSA',
'PERIODO' => '08:00 - 12:00',
'ID' => 'Z7526',
'END' => 'R P1000, FD',
'CONTRATO' => '799644',
'AREA' => 'AR01',
'ASSINANTE' => 'DAVI',
'BAIRRO' => 'BEATRIZ',
'OBS' => ['Agendamento'],
'TEL RES' => '42988674761',
],
[
'CIDADES' => 'PONTA GROSSA',
'PERIODO' => '08:00 - 12:00',
'ID' => 'Z0979',
'END' => 'R J93, FD',
'CONTRATO' => '79490',
'AREA' => 'AR01',
'ASSINANTE' => 'FERNANDES REIS',
'BAIRRO' => 'UVARANAS',
'OBS' => ['Agendamentoente'],
'TEL RES' => '4289986',
],
];
$secondArray = [
[
'id' => 1,
'table' => 'id_operacao',
'sheet' => 'CIDADES',
],
[
'id' => 2,
'table' => 'horario',
'sheet' => 'PERIODO',
],
[
'id' => 3,
'table' => 'tipo_wo',
'sheet' => 'TIPO DE SERVICO',
],
[
'id' => 4,
'table' => 'tecnico_id',
'sheet' => 'ID',
],
[
'id' => 5,
'table' => 'contrato',
'sheet' => 'CONTRATO',
],
[
'id' => 6,
'table' => 'roteamento',
'sheet' => 'AREA',
],
[
'id' => 7,
'table' => 'endereco',
'sheet' => 'END',
],
[
'id' => 8,
'table' => 'nome_cliente',
'sheet' => 'ASSINANTE',
],
];
//I guess this is what you were missing most
$oldKeysToNewKeys = array_combine(
array_column($secondArray, 'sheet'),
array_column($secondArray, 'table')
);
foreach ($firstArray as $key => $firstArrayElements) {
$newFirstArrayElement = [];
foreach ($firstArrayElements as $oldKey => $value) {
//You could add checks to avoid errors when keys are not set etc..
$newKey = $oldKeysToNewKeys[$oldKey];
$newFirstArrayElement[$newKey] = $value;
}
$firstArray[$key] = $newFirstArrayElement;
}
//There you go!
var_dump($firstArray);

access single value of php object array

I call an api and the response i get is
Array (
[meta] => Array (
[code] => 200
[type] => Success
[message] => Success
)
[data] => Array (
[items] => Array (
[0] => Array (
[id] => b4a235596fd9550dfb69f181f4db007f
[tracking_number] => 2649884668232181
[carrier_code] => hermes
[order_create_time] =>
[destination_code] =>
[status] => delivered
[track_update] =>
[original_country] =>
[itemTimeLength] => 7
[stayTimeLength] => 74
[service_code] =>
[packageStatus] =>
[substatus] =>
[last_mile_tracking_supported] =>
[origin_info] => Array (
[ItemReceived] => 2019-04-09 09:29
[ItemDispatched] =>
[DepartfromAirport] =>
[ArrivalfromAbroad] =>
[CustomsClearance] =>
[DestinationArrived] =>
[weblink] => https://www.hermesworld.com/en/
[phone] =>
[carrier_code] => hermes
[trackinfo] => Array (
[0] => Array (
[Date] => 2019-04-15 11:51
[StatusDescription] => Posted through letterbox
[Details] =>
[checkpoint_status] => delivered
)
[1] => Array (
[Date] => 2019-04-15 09:45
[StatusDescription] => Delivery will be attempted between 10:00 and 14:00 today
[Details] =>
[checkpoint_status] => transit
)
[2] => Array (
[Date] => 2019-04-15 06:39
[StatusDescription] => On its way to the courier
[Details] =>
[checkpoint_status] => transit
)
[3] => Array (
[Date] => 2019-04-14 22:33
[StatusDescription] => At the customers local depot
[Details] =>
[checkpoint_status] => transit
)
.....
)
)
[destination_info] =>
[lastEvent] => Posted through letterbox,2019-04-15 11:51
[lastUpdateTime] => 2019-04-15 11:51
)
)
)
) 1
I would like to access the value of checkpoint_status but im not getting there using the following ways:
response in variable
$track = print_r($track);
1. $track['checkpoint_status']
2. $track[0] // just to see if it returns anything, but no result
3. $track[1] // just to see if it returns anything, but no result
4. array_column($track, 'checkpoint_status'); // returns nothing
You need to loop, to get all checkpoint_status
foreach($array['data']['items'] as $item){
foreach($item['origin_info']['trackinfo'] as $trackinfo){
echo $trackinfo['checkpoint_status'].PHP_EOL;
}
}
Sample output:-https://3v4l.org/IM7I1
You can use array_walk_recursive
$r = [];
array_walk_recursive($a, function($v, $k) use(&$r){
($k == 'checkpoint_status') ? ($r[]=$v) : '';
});
https://3v4l.org/rCVEB
$response = [
'meta' => [
'code' => 200,
'type' => 'Success',
'message' => 'Success',
],
'data' => [
'items' => [
'0' => [
'id' => 'b4a235596fd9550dfb69f181f4db007f',
'tracking_number' => '2649884668232181',
'carrier_code' => 'hermes',
'order_create_time' => null,
'destination_code' => null,
'status' => 'delivered',
'track_update' => null,
'original_country' => null,
'itemTimeLength' => 7,
'stayTimeLength' => 74,
'service_code' => null,
'packageStatus' => null,
'substatus' => null,
'last_mile_tracking_supported' => null,
'origin_info' => [
'ItemReceived' => '2019-04-09 09:29',
'ItemDispatched' => null,
'DepartfromAirport' => null,
'ArrivalfromAbroad' => null,
'CustomsClearance' => null,
'DestinationArrived' => null,
'weblink' => 'https://www.hermesworld.com/en/',
'phone' => null,
'carrier_code' => 'hermes',
'trackinfo' => [
'0' => [
'Date' => '2019-04-15 11:51',
'StatusDescription' => 'Posted through letterbox',
'Details' =>null,
'checkpoint_status' => 'delivered',
],
'1' => [
'Date' => '2019-04-15 09:45',
'StatusDescription' => 'Delivery will be attempted between 10:00 and 14:00 today',
'Details' => null,
'checkpoint_status' => 'transit',
],
'2' => [
'Date' => '2019-04-15 06:39',
'StatusDescription' => 'On its way to the courier',
'Details' =>null,
'checkpoint_status' => 'transit',
],
'3' => [
'Date' => '2019-04-14 22:33',
'StatusDescription' => 'At the customers local depot',
'Details' => null,
'checkpoint_status' => 'transit',
],
]
],
'destination_info' => null,
'lastEvent' => 'Posted through letterbox,2019-04-15 11:51',
'lastUpdateTime' => '2019-04-15 11:51',
]
]
]
];
If you are working on development mode you could turn on display errors on php and may get this result:
echo $response['checkpoint_status']; // won't work as response array has no checkpoint_status keyed array
echo $response[0]; // won't work as response array has no 0 keyed array
echo $response[1]; // won't work as response array has no 1 keyed array
print_r(array_column($response, 'checkpoint_status')); // won't work as response array has no column checkpoint_status
There are many ways in which you could get your result one of which is given below:
$trackinfo = $response['data']['items'][0]['origin_info']['trackinfo'];
$checkpoint_status = array_column($trackinfo, 'checkpoint_status');
print_r($checkpoint_status);
Result:
Array (
[0] => delivered
[1] => transit
[2] => transit
[3] => transit
)

ElasticSearch - How to return data from elastic search with not empty value?

I've got a problem with eliminating empty values from a document of one of my index.
$params = [
"scroll" => "30s", // how long between scroll requests. should be small!
"size" => 1,
"index" => $eddIndex,
'type' => $eddIndexType
];
$response = $client->search ( $params );
while ( isset ( $response ['hits']['hits'] ) && count ( $response['hits']['hits'] ) > 0 ) {
$scroll_id = $response ['_scroll_id'];
$response = $client->scroll ( [
"scroll_id" => $scroll_id,
"scroll" => "30s"
] )
;
This will Return
Array
(
[_scroll_id] => cXVlcnlUaGVuRmV0Y2g7NTs0NTY0NDM6di1Bd2x4X0ZSaTJ5cnpVUkFHb3FRdzs0NTY0NDQ6di1Bd2x4X0ZSaTJ5cnpVUkFHb3FRdzs0NTY0NDY6di1Bd2x4X0ZSaTJ5cnpVUkFHb3FRdzs0NTY0NDc6di1Bd2x4X0ZSaTJ5cnpVUkFHb3FRdzs0NTY0NDU6di1Bd2x4X0ZSaTJ5cnpVUkFHb3FRdzswOw==
[took] => 12
[timed_out] =>
[_shards] => Array
(
[total] => 5
[successful] => 5
[failed] => 0
)
[hits] => Array
(
[total] => 378887
[max_score] => 1
[hits] => Array
(
[0] => Array
(
[_index] => index
[_type] => edd
[_id] => 13038
[_score] => 1
[_source] => Array
(
[reason] =>
[booking_date] => 2013-05-03T18:30:00.000Z
[booking_location] => ABC
[scan_edd] =>
[call_status] => Call
[patient_name] => ABCD
[#version] => 1
[effective_edd] =>
[id] => 13038
[email] => xxxxxxxxx#gmail.com
[last_known_edd] =>
[booking_amount] => 8000
[address] => xxxxxxxxxxxxxxxxx
[eda] => 2013-09-09T18:30:00.000Z
[edd] =>
[mpi] => xxxxxxx
[mobile] => xxxxxxx
[statuss] => Open Payment
[tags] => Array
(
[0] => edd
)
[last_consult_by] => Dr. XXXX [site] => BLR
[#timestamp] => 2018-07-06T06:30:39.040Z
[patient_id] => 75220
[last_consult_on] => 2014-02-28T18:30:00.000Z
[ip_booking] => XYX Package
[is_converted] => 0
)
)
)
)
)
If you look at my output, There is a field [effective_edd] returning empty.
I wanted to return data with [effective_edd] not empty.
I'm referring to the below document https://packagist.org/packages/elasticsearch/elasticsearch
You need to add a query that checks for the existence of the field to your scroll request:
$params = [
"scroll" => "30s", // how long between scroll requests. should be small!
"size" => 1,
"index" => $eddIndex,
'type' => $eddIndexType,
'body' => [
'query' => [
'exists' => [
'field' => 'effective_edd'
]
]
]
];

how to sort array data in alphabetic key order in php

my collection of data in array which is shown below the index key is A,B,C but i want to store these key in "key" and its key letter's words in "dishes" key
array:3 [
"A" => array:4 [
0 => 37
1 => "Algerian"
2 => 6
3 => "American"
]
"B" => array:6 [
0 => 27
1 => "Belgian"
2 => 20
3 => "Brazilian"
]
and so on..
i wanna sort this array like aplhabetic order as shown below
array:10 [
0 => array:2 [
"key" => "A"
"dishes" => array:2 [
0=>array:2[
"id" => 37
"type" => "Algerian"
],
1=>array:2[
"id" => 6
"type" => "American"
]
]
]
1 => array:2 [
"key" => "B"
"dishes" => array:2 [
0=>array:2[
"id" => 27
"type" => "Belgian"
],
1=>array:2[
"id" => 20
"type" => "Brazilian"
]
]
]
and so on...
This would be a possible solution:
<?php
$input = [
'A' => [
0 => 37,
1 => "Algerian",
2 => 6,
3 => "American"
],
'B' => [
0 => 27,
1 => "Belgian",
2 => 20,
3 => "Brazilian"
]
];
$output = [];
array_walk($input, function($values, $key) use (&$output) {
$entry = [
'key' => $key,
'dishes' => []
];
foreach(array_chunk($values, 2) as $chunk) {
$entry['dishes'][] = [
'id' => $chunk[0],
'type' => $chunk[1]
];
}
$output[] = $entry;
});
print_r($output);
The output of above code obviously is:
Array
(
[0] => Array
(
[key] => A
[dishes] => Array
(
[0] => Array
(
[id] => 37
[type] => Algerian
)
[1] => Array
(
[id] => 6
[type] => American
)
)
)
[1] => Array
(
[key] => B
[dishes] => Array
(
[0] => Array
(
[id] => 27
[type] => Belgian
)
[1] => Array
(
[id] => 20
[type] => Brazilian
)
)
)
)
You have to loop through the original array to create your new structure. Then you can use the ksort function to sort them.
$newArr = new array();
for ($arr as $elem) {
$dishArr = new array();
for($elem['dishes'] as $dish) {
$dishArr[] = $dish['id'];
$dishArr[] = $dish['type'];
}
$newArr[$elem['key']] = $dishArr;
}
ksort($newArr);

Categories