access single value of php object array - php

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
)

Related

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

Php check and replace if value exist in multi array?

Problem:
I dont know/understand how to check if date and place exists on the same "row" and they exists more then once.
Second, how do i then merge an array
my case MergeArray with ArraySchedule
Code:
$ArraySchedule = array();
while ($data = $stmt -> fetch(PDO::FETCH_ASSOC)) {
$schedules = array(
"id" => $data['id'],
"name" => $data['name'],
"date" => $data['date'],
"time" => $data['time'],
"place_id" => $data['place_id'],
"place" => $data['place'],
);
array_push($ArraySchedule, $schedules);
}
$dupe_array = array();
foreach ($ArraySchedule as $key => $value) {
if(++$dupe_array[$value["date"]] > 1 && ++$dupe_array[$value["place_id"]] > 1 ){
// this statement is wrong, i want something like:
// if date and place_id exists on the same "row" and they exists more then once
}
}
What i want to do:
Check if ArraySchedule contains schedules that have the same date and place,
if there is more than one schedule that has the same date and place_id.
then I want to update ArraySchedule with this structure
$MergeArray = array(
"id" => ArraySchedule['id'],
"name" => array(
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
"name" => scheduleSameDateAndPlace['name'],
),
"date" => $ArraySchedule['date'],
"time" => $ArraySchedule['time'],
"place_id" => $ArraySchedule['place_id'],
"place_name" => $ArraySchedule['place_name'],
),
MergeArray with ArraySchedule?
anyway...
Output I think I want?
Print_r($ArraySchedule)
array(
[0] =>
array(
[id] => 1
[names] => Simon
[date] => 2019-01-02
[time] 18.00
[place_id] => Tystberga Park
[place] => Tystberga
)
[1] =>
array(
[id] => 2
//[names] insted of [name]?
[names] =>
array(
[name] => Vincent
[name] => Angel
[name] => Kim
)
[date] => 2019-02-17
[time] => 13.00
[place_id] => Borås Park
[place] => Borås
)
[2] =>
array(
[id] => 3
// [names] is always an array?
[names] => Caitlyn
[date] => 2019-03-15
[time] 13.00
[place_id] => Plaza Park
[place] => EvPark
)
)
You can use array-reduce. Consider the following:
function mergeByDateAndPlace($carry, $item) {
$key = $item["place_id"] . $item["date"]; // creating key matching exact place and date
if (!isset($carry[$key])) {
$carry[$key]["name"] = $item["name"];
} else {
$carry[$key] = $item;
$item["name"] = [$item["name"]]; // make default array with 1 element so later can be append other names
}
return $carry;
}
Now use it with:
$MergeArray = array_reduce($ArraySchedule, "mergeByDateAndPlace", []);
If you later want to know if there were any duplicate you can just loop on $MergeArray. You can also use array_values if you want to discard the concat keys.
Notice #Nick 2 important comment about saving the first loop and the "time" value that need to be decided. Also notice your desire output contain multi element with the same key ("name") - you need to append them with int key - Array can not have duplicate keys.
Hope that helps!
Here is my data from my database:
var_export($ArraySchedule)
array (
0 => array ( 'id' => '225', 'place_id' => 'Alviks Kulturhus', 'name' => 'BarraBazz', 'date' => '2019-03-19', 'placeadress' => 'Gustavslundsvägen 1', ),
1 => array ( 'id' => '229', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Anders Björk', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
2 => array ( 'id' => '230', 'place_id' => 'Axelhuset Göteborg', 'name' => 'Black Jack', 'date' => '2019-04-08', 'placeadress' => 'Axel Dahlströms torg 3', ),
3 => array ( 'id' => '227', 'place_id' => 'Arosdansen Syrianska Kulturcentret', 'name' => 'BarraBazz', 'date' => '2019-05-08', 'placeadress' => 'Narvavägen 90', ),
4 => array ( 'id' => '228', 'place_id' => 'Aspåsnäset', 'name' => 'Blender', 'date' => '2019-05-25', 'placeadress' => 'Aspåsnäset 167', ),
5 => array ( 'id' => '226', 'place_id' => 'Arenan Västervik Resort', 'name' => 'Blender', 'date' => '2019-06-29', 'placeadress' => 'Lysingsvägen', ),
6 => array ( 'id' => '222', 'place_id' => 'Alingsåsparken', 'name' => 'Bendéns', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
7 => array ( 'id' => '223', 'place_id' => 'Alingsåsparken', 'name' => 'Charlies', 'date' => '2019-07-16', 'placeadress' => 'Folkparksgatan 3A', ),
8 => array ( 'id' => '224', 'place_id' => 'Allhuset Södertälje', 'name' => 'Cedrix', 'date' => '2019-07-16', 'placeadress' => 'Barrtorpsvägen 1A', ), )
I want to update the "name" with an array of names everytime that place_id and date are the same.
This is the output I want:
Array (
[0] =>
Array ( [id] => 225 [place_id] => Alviks Kulturhus [name] => BarraBazz [date] => 2019-03-19 [placeadress] => Gustavslundsvägen 1 )
[1] =>
Array ( [id] => 229 [place_id] => Axelhuset Göteborg [name] => Array([0] => Anders Björk [1] => Black Jack ) [date] => 2019-04-08 [placeadress] => Axel Dahlströms torg 3 )
[3] =>
Array ( [id] => 227 [place_id] => Arosdansen Syrianska Kulturcentret [name] => BarraBazz [date] => 2019-05-08 [placeadress] => Narvavägen 90 )
[4] =>
Array ( [id] => 228 [place_id] => Aspåsnäset [name] => Blender [date] => 2019-05-25 [placeadress] => Aspåsnäset 167 )
[5] =>
Array ( [id] => 226 [place_id] => Arenan Västervik Resort [name] => Blender [date] => 2019-06-29 [placeadress] => Lysingsvägen )
[6] =>
Array ( [id] => 222 [place_id] => [Alingsåsparken] [name] => Array([0] => Bendéns [1] => Charlies) [date] => 2019-07-16 [placeadress] => Folkparksgatan 3A )
[8] =>
Array ( [id] => 224 [place_id] => Allhuset Södertälje [name] => Cedrix [date] => 2019-07-16 [placeadress] => Barrtorpsvägen 1A ) )
Here is my updated code
$sql = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` ORDER BY `date`";
$stmt = $db -> prepare($sql);
$stmt -> execute();
$ArraySchedule = $stmt->fetchAll(PDO::FETCH_ASSOC);
var_export($ArraySchedule);
$DatePlace = array();
foreach ($ArraySchedule as $key => $Schedule){
$Arrayquery = "SELECT `schedule`.`id`,`schedule`.`place_id`,`schedule`.`name`,`schedule`.`date`,`places`.`placeadress` FROM `schedule` INNER JOIN `places` ON `schedule`.`place_id`=`places`.`place_id` WHERE `schedule`.`date`= :date_ AND `schedule`.`place_id` = :place_id ORDER BY `date`";
$ArrayStmt = $db->prepare($Arrayquery);
$ArrayStmt -> execute(array(":date_" => $Schedule['date'],":place_id" => $Schedule['place_id']));
//Getting every $Schedule that has the same date and place_id
if($ArrayStmt->rowCount() > 1){
//Here i want two update the name inside
//$ArrayArraySchedule with an array of names
//that has the same place and date?
}
}
print_r($ArraySchedule);

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 get the highest and lowest Values and sum from Multidimensional array in PHP

I have tried using this example here Return index of highest value in an array
But that does not go into a multi dimensional Array
I have tried ARRAY_COLUMN(), array_values(), array_shift, Max and Min but they are not getting the info i need
I want to be able to loop thru and get to:
[pricing]
then Check pricing to see which is the highest and lowest in the nested array
so like below which total was the Highest and lowest trades on these dates
[2017-09-22]
[2017-09-23]
obviously [2017-09-23] is a simple one, i just dint want to add much more code for ppl helping to go thru.
The Array i create looks like this:
Array
(
[2017-09-23] => Array
(
[0] => Array
(
[timestamp] => 1506169387000
[pricing] => 9.5470
[qty] => 25
[total] => 238.675
[date] => 2017-09-23
)
)
[2017-09-22] => Array
(
[0] => Array
(
[timestamp] => 1506093083000
[pricing] => 9.6300
[qty] => 25
[total] => 240.75
[date] => 2017-09-22
)
[1] => Array
(
[timestamp] => 1506077220000
[pricing] => 8.7190
[qty] => 13
[total] => 113.347
[date] => 2017-09-22
)
[2] => Array
(
[timestamp] => 1506077109000
[pricing] => 8.6800
[qty] => 83
[total] => 720.44
[date] => 2017-09-22
)
[3] => Array
(
[timestamp] => 1506065258000
[pricing] => 8.7100
[qty] => 25
[total] => 217.75
[date] => 2017-09-22
)
)
in the example above i would like it to Create a new array with only the following
date -> last timestamp -> Highest pricing -> Lowest lowest -> Total of all Totals -> first Timestamp
EDIT: the last and first Timestamp are basically the first and last index so in this case:
[timestamp] => 1506093083000 and [timestamp] => 1506065258000
or Index [0] and index [3]
The array from your question:
$array = array (
'2017-09-23' =>
array (
0 =>
array (
'timestamp' => '1506169387000',
'pricing' => '9.5470',
'qty' => '25',
'total' => '238.675',
'date' => '2017-09-23',
),
),
'2017-09-22' =>
array (
0 =>
array (
'timestamp' => '1506093083000',
'pricing' => '9.6300',
'qty' => '25',
'total' => '240.75',
'date' => '2017-09-22',
),
1 =>
array (
'timestamp' => '1506077220000',
'pricing' => '8.7190',
'qty' => '13',
'total' => '113.347',
'date' => '2017-09-22',
),
2 =>
array (
'timestamp' => '1506077109000',
'pricing' => '8.6800',
'qty' => '83',
'total' => '720.44',
'date' => '2017-09-22',
),
3 =>
array (
'timestamp' => '1506065258000',
'pricing' => '8.7100',
'qty' => '25',
'total' => '217.75',
'date' => '2017-09-22',
),
),
);
To get the values maybe you can use array_map and with this the function array_column is the key of all, try with this:
$values = array_map(function($dates) {
$timestamps = array_column($dates, 'timestamp');
$pricings = array_column($dates, 'pricing');
return [
'max_pricing' => max($pricings),
'lowest_pricing' => min($pricings),
'total_of_totals' => array_sum(array_column($dates, 'total')),
'first_timestamp' => reset($timestamps),
'last_timestamp' => end($timestamps),
];
}, $array);
$values is an array with the filter values that you need:
Array
(
[2017-09-23] => Array
(
[max_pricing] => 9.5470
[lowest_pricing] => 9.5470
[total_of_totals] => 238.675
[first_timestamp] => 1506169387000
[last_timestamp] => 1506169387000
)
[2017-09-22] => Array
(
[max_pricing] => 9.6300
[lowest_pricing] => 8.6800
[total_of_totals] => 1292.287
[first_timestamp] => 1506093083000
[last_timestamp] => 1506065258000
)
)
EDIT
Get the pricing of the [first_timestamp] and [last_timestamp]
$values = array_map(function($dates) {
$timestamps = array_column($dates, 'timestamp');
$pricings = array_column($dates, 'pricing');
return [
'max_pricing' => max($pricings),
'lowest_pricing' => min($pricings),
'total_of_totals' => array_sum(array_column($dates, 'total')),
'first_timestamp' => [
'value' => reset($timestamps),
'pricing' => $pricings[each($timestamps)['key']]
],
'last_timestamp' => [
'value' => end($timestamps),
'pricing' => $pricings[each($timestamps)['key']]
]
];
}, $array);
I added an array to both timestamps with the value of these and the pricing.
Array
(
[2017-09-23] => Array
(
[max_pricing] => 9.5470
[lowest_pricing] => 9.5470
[total_of_totals] => 238.675
[first_timestamp] => Array
(
[value] => 1506169387000
[pricing] => 9.5470
)
[last_timestamp] => Array
(
[value] => 1506169387000
[pricing] => 9.5470
)
)
[2017-09-22] => Array
(
[max_pricing] => 9.6300
[lowest_pricing] => 8.6800
[total_of_totals] => 1292.287
[first_timestamp] => Array
(
[value] => 1506093083000
[pricing] => 9.6300
)
[last_timestamp] => Array
(
[value] => 1506065258000
[pricing] => 8.7100
)
)
)

codeigniter insert multi-dimensional array to the database

Hello I have this multi dimensional array which needs to be inserted to the database table.
so far I have come up with this solution which don't work fully. I have a form that support dynamic fields many dynamic fields. I want to save those dynamically created fields using this function. First I had been able to create a loop to format the data.
I used this loop to format the data
$url = str_replace(' ','-',strtolower($this->input->post('title')));
$data = ['business' => [
'title' => $this->input->post('title'),
'URL' => $url,
'category' => $this->input->post('category'),
'region' => $this->input->post('region')
],
'description_' => [
'text' => $this->input->post('description'),
],
'logo_' => [
'blob' => $this->input->post('logo'),
]];
$nyingi = [ 'location_' => ['text' => 'loc_txt','priority' => 'loc_order'],
'photo_' => ['path' => 'p_txt'],
'video_' => ['path' => 'v_txt'],
'product_' => ['p_id' => 'pt_q', 'text' => 'pt_txt', 'expire' => 'pt_xpr', 'title' => 'pt_tt'],
'service_' => ['p_id' => 'st_q', 'text' => 'st_txt', 'expire' => 'st_xpr', 'title' => 'st_tt'],
'hours_' => ['time1' => 't1', 'time2' => 't2', 'type' => 'tt'],
'map_' => ['text' => 'm_txt']
];
foreach($nyingi as $ins => $vl){
foreach($vl as $fld => $box){
$uwazi = $this->input->post($box);
if(is_array($uwazi) && 1<count($uwazi)){
foreach($uwazi as $bb){
$one[$ins][$fld][] = $bb;
}
} elseif(is_array($uwazi) && 1==count($uwazi)) {
print_r($uwazi);
}
}
}
for($g=0;$g<count($one);$g++){
for($h=0;$h<count($one[$g]);$h++){
for($z=0;$z<count($one[$g][$h]);$z++){
//if(array_key_exists($one[$g][$h+1], $one)){
print $one[$g][$h][$z+1];
//}
}
}
}
$data = array_merge($data, $one);
The output of the above code
[location_] => Array
(
[text] => Array
(
[0] => Lemara Main Office
[1] => Themi branch
[2] => Sinoni branch
)
[priority] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
)
[photo_] => Array
(
[path] => Array
(
[0] => lemaraphoto.png
[1] => themiphoto.png
[2] => sinoniphoto.png
)
)
[video_] => Array
(
[path] => Array
(
[0] => lemaravideo.mp4
[1] => themivideo.mp4
[2] => sinonivideo.mp4
)
)
[product_] => Array
(
[p_id] => Array
(
[0] => product photo
[1] => product 3 photo
[2] => Product 2 photo
)
[text] => Array
(
[0] => product desc
[1] => product 3 desc
[2] => product 2 desc
)
[expire] => Array
(
[0] => product expire
[1] => product 3 expire
[2] => Product 2 expire
)
[title] => Array
(
[0] => product
[1] => Product 3
[2] => Product 2
)
)
[service_] => Array
(
[p_id] => Array
(
[0] => Service 2 photo
[1] => service 3 photo
[2] => service photo
)
[text] => Array
(
[0] => service 2 desc
[1] => service 3 desc
[2] => service desc
)
[expire] => Array
(
[0] => Service 2 expire
[1] => service 3 expire
[2] => service expire
)
[title] => Array
(
[0] => Service 2
[1] => service 3
[2] => service
)
)
)
I have this add_bz function
function add_bz($data){
$this->db->trans_start(); $er=0;
foreach($data as $table => $sql){
if($table==="business"){
$this->db->insert($table, $sql);
$id = $this->db->insert_id();
} else {
array_merge($sql, array('idd' => $id));
$this->db->insert($table, $sql);}
}
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE){print "Transaction Fails";return FALSE;}
return TRUE;
}
That function allows me to insert the data in this format only.
[[business] => Array
(
[title] => Email Marketing
[URL] => email-marketing
[category] => 3
[region] => 2
)
[description_] => Array
(
[text] => Some desc
)
[logo_] => Array
(
[blob] => mainlogo.png
)
]
as business, decription_, logo_ are db tables where title, URL, category, region, text, blob are the db columns to the corresponding tables and the rest is data that goes to those columns.
How I want it to works. For example in location_
I want to the array to change into my working format or something else that will work like this
location_ => ['text' => [[0] => 'Lemara Main Office'],
'priority' => [[0] => '1']
]
location_ => ['text' => [[1] => 'Themi Office'],
'priority' => [[1] => '2']
]
location_ => ['text' => [[2] => 'Sinoni Office'],
'priority' => [[2] => '3']
]
or like this
location_ => [0 => [['text' => 'Lemara Main Office'],
['priority' => '1']
],
1 => [['text' => 'Themi Main Office'],
['priority' => '2']
],
2 => [['text' => 'Sinoni Main Office'],
['priority' => '3']
]
],
And also support many columns not just the two.
Any help is deeply appreciated as I have been struggling for days to make this work. Thanks in advance.
I would suggest you convert your array to JSON String then insert it to DB as text.
JSON would handle your multidimentional data so well,
To convert your array to JSON : http://php.net/manual/en/function.json-encode.php
To convert your JSON to Array : http://php.net/manual/en/function.json-decode.php

Categories