Get specific data from the array - php

Since I'm really unexperienced with PHP, I'm having trouble retrieving specific data from the following array that I receive via API:
I need the values of
'id'
'amount'
'statsTags'
Unfortunatly the following code retrieves an undefined index error:
echo $commissions['TPerformant\API\Model\Commission::__set_state']['id'];
This is the content of the var_dump
var_dump($commissions):
array (
0 =>
TPerformant\API\Model\Commission::__set_state(array(
'id' => 457171,
'userId' => 8917,
'actionid' => 456657,
'actiontype' => 'sale',
'amount' => '0.31',
'status' => 'pending',
'affrequestId' => NULL,
'description' => 'cosmetics|Mascara Extra Super Lash Curved Brush 8 mlx1 (7% from 6.66), cosmetics|Sampon uscat Blush Dry 50 mlx1 (7% from 8.33), cosmetics|Crema de maini si corp cu Lavandax1 (7% from 4.99)',
'createdAt' => '2016-12-24T16:48:07Z',
'updatedAt' => '2016-12-24T16:48:07Z',
'reason' => NULL,
'statsTags' => ',undefinedDesktopnulla60949bd-0b06-4fd6-a324-0d65351c10e9,',
'history' => NULL,
'currency' => 'EUR',
'workingCurrencyCode' => 'RON',
'programId' => 882,
'amountInWorkingCurrency' => '1.4',
'program' =>
TPerformant\API\Model\AffiliateProgram::__set_state(array(
'affrequest' => NULL,
'id' => NULL,
'slug' => 'elefant-ro',
'name' => 'elefant.ro ',
'mainUrl' => NULL,
'baseUrl' => NULL,
'description' => NULL,
'activatedAt' => NULL,
'userId' => NULL,
'uniqueCode' => NULL,
'status' => NULL,
'cookieLife' => NULL,
'tos' => NULL,
'productFeedsCount' => NULL,
'productsCount' => NULL,
'bannersCount' => NULL,
'approvalTime' => NULL,
'currency' => NULL,
'enableLeads' => NULL,
'enableSales' => NULL,
'defaultLeadCommissionRate' => NULL,
'defaultLeadCommissionType' => NULL,
'defaultSaleCommissionRate' => NULL,
'defaultSaleCommissionType' => NULL,
'approvedCommissionCountRate' => NULL,
'approvedCommissionAmountRate' => NULL,
'paymentType' => 'postpaid',
'balanceIndicator' => NULL,
'downtime' => NULL,
'averagePaymentTime' => NULL,
'logoId' => NULL,
'logoPath' => NULL,
'userLogin' => 'elefant',
'category' => NULL,
'countries' => NULL,
'ignoreIPs' => NULL,
'requester' =>
TPerformant\API\HTTP\Affiliate::__set_state(array(
'accessToken' =>
array (
0 => 'notrelevant',
),
'clientToken' =>
array (
0 => 'notrelevant',
),
'uid' =>
array (
0 => 'notrelevant',
),
'userData' =>
TPerformant\API\Model\Affiliate::__set_state(array(
'id' => 8917,
'email' => 'notrelevant',
'login' => 'notrelevant',
'name' => 'notrelevant',
'role' => 'affiliate',
'uniqueCode' => 'notrelevant',
'createdAt' => '2012-04-17T10:25:11Z',
'avatarUrl' => 'https://secure.gravatar.com/avatar/2aa7cbeda20ce7dee64a2764004ef7b5?d=https://network.2performant.com%2Fimg%2Favatar-default.jpg',
'newsletterSubscription' => true,
'userInfo' =>
stdClass::__set_state(array(
'address' => 'Bucuresti',
'city' => 'Bucuresti',
'country' => 'Romania',
'display_name' => 'regular',
'firstname' => 'Andrei',
'lastname' => 'Ioniță',
'organization' => '',
'phone' => '',
'state' => 'Bucuresti',
'typeofbusiness' => '',
)),
'requester' => NULL,
)),
)),
)),
'publicActionData' =>
stdClass::__set_state(array(
'created_at' => '2016-12-24T16:48:07Z',
'updated_at' => '2016-12-24T16:48:07Z',
'rate' => '7.0',
'amount' => '4.41',
'ad_type' => 'quicklink',
'ad_id' => '882',
'source_ip' => '109.99.30.73',
'description' => 'cosmetics|Mascara Extra Super Lash Curved Brush 8 mlx1 (7% from 6.66), cosmetics|Sampon uscat Blush Dry 50 mlx1 (7% from 8.33), cosmetics|Crema de maini si corp cu Lavandax1 (7% from 4.99)',
'working_currency_code' => 'RON',
'amount_in_working_currency' => '19.98',
)),
'publicClickData' =>
stdClass::__set_state(array(
'created_at' => '2016-12-24T16:13:20Z',
'source_ip' => '109.99.30.73',
'url' => 'https://www.maller.ro/voucher-elefant-ro-40-reducere/',
'redirect_to' => 'http://www.elefant.ro/oferte-speciale#utm_source=2parale&utm_medium=Campaign&utm_campaign=2c42f3c4e',
'stats_tags' => ',undefinedDesktopnulla60949bd-0b06-4fd6-a324-0d65351c10e9,',
)),
'requester' =>
TPerformant\API\HTTP\Affiliate::__set_state(array(
'accessToken' =>
array (
0 => 'notrelevant',
),
'clientToken' =>
array (
0 => 'notrelevant',
),
'uid' =>
array (
0 => 'notrelevant',
),
'userData' =>
TPerformant\API\Model\Affiliate::__set_state(array(
'id' => 8917,
'email' => 'notrelevant',
'login' => 'notrelevant',
'name' => 'Andrei Ioniță',
'role' => 'affiliate',
'uniqueCode' => 'notrelevant',
'createdAt' => '2012-04-17T10:25:11Z',
'avatarUrl' => 'https://secure.gravatar.com/avatar/2aa7cbeda20ce7dee64a2764004ef7b5?d=https://network.2performant.com%2Fimg%2Favatar-default.jpg',
'newsletterSubscription' => true,
'userInfo' =>
stdClass::__set_state(array(
'address' => 'Bucuresti',
'city' => 'Bucuresti',
'country' => 'Romania',
'display_name' => 'regular',
'firstname' => 'Andrei',
'lastname' => 'Ioniță',
'organization' => '',
'phone' => '',
'state' => 'Bucuresti',
'typeofbusiness' => '',
)),
'requester' => NULL,
)),
)),
)),

Related

Laravel - Validate at least one field from an array

I have this data:
[2022-12-07 11:56:19] local.INFO: array (
'name' => NULL,
'import_period' => NULL,
'google_ads_account' => NULL,
'period' => NULL,
'period_date_from' => NULL,
'period_date_to' => NULL,
'id_campaigns' =>
array (
0 =>
array (
'id_campaign' => NULL,
),
),
'id_adgroups' =>
array (
0 =>
array (
'id_adgroup' => NULL,
),
),
'campaign_name_contains' => NULL,
'adgroup_name_contains' => NULL,
'click' => 'less_than',
'click_value' => NULL,
'click_from' => NULL,
'click_to' => NULL,
'impressions' => 'less_than',
'impressions_value' => NULL,
'impressions_from' => NULL,
'impressions_to' => NULL,
'cost' => 'less_than',
'cost_value' => NULL,
'cost_from' => NULL,
'cost_to' => NULL,
'conversions' => 'less_than',
'conversions_value' => NULL,
'conversions_from' => NULL,
'conversions_to' => NULL,
'mapping_list' =>
array (
0 =>
array (
'value' => 'conversions',
'text' => NULL,
),
1 =>
array (
'value' => 'roas',
'text' => NULL,
),
2 =>
array (
'value' => 'all_conversions',
'text' => NULL,
),
3 =>
array (
'value' => 'all_conversions_from_interactions_rate',
'text' => NULL,
),
4 =>
array (
'value' => 'ctr',
'text' => NULL,
),
5 =>
array (
'value' => 'average_cpc',
'text' => NULL,
),
6 =>
array (
'value' => 'clicks',
'text' => NULL,
),
7 =>
array (
'value' => 'impressions',
'text' => NULL,
),
8 =>
array (
'value' => 'cost',
'text' => NULL,
),
9 =>
array (
'value' => 'conversions_value',
'text' => NULL,
),
10 =>
array (
'value' => 'conversions_from_interactions_rate',
'text' => NULL,
),
11 =>
array (
'value' => 'cost_per_conversion',
'text' => NULL,
),
12 =>
array (
'value' => 'search_click_share',
'text' => NULL,
),
13 =>
array (
'value' => 'search_impression_share',
'text' => NULL,
),
14 =>
array (
'value' => 'value_per_all_conversions',
'text' => NULL,
),
15 =>
array (
'value' => 'value_per_conversion',
'text' => NULL,
),
),
)
I am validating this data like this:
$validator = Validator::make($request->all(), [
'name' => 'required',
'import_period' => 'required',
'google_ads_account' => 'required',
'period' => 'required',
'period_date_from' => 'required_if:period,custom',
'period_date_to' => 'required_if:period,custom',
'id_campaigns.*.id_campaign'=> 'required',
'id_adgroups.*.id_adgroup' => 'required',
'campaign_name_contains' => 'required',
'adgroup_name_contains' => 'required',
'mapping_list.*.text' => 'required|min:1',
'click' => 'required',
'click_value' => 'required_if:click,greater_than,less_than',
'click_from' => 'required_if:click,between',
'click_to' => 'required_if:click,between',
'cost' => 'required',
'cost_value' => 'required_if:cost,greater_than,less_than',
'cost_from' => 'required_if:cost,between',
'cost_to' => 'required_if:cost,between',
'impressions' => 'required',
'impressions_value' => 'required_if:impressions,greater_than,less_than',
'impressions_from' => 'required_if:impressions,between',
'impressions_to' => 'required_if:impressions,between',
'conversions' => 'required',
'conversions_value' => 'required_if:conversions,greater_than,less_than',
'conversions_from' => 'required_if:conversions,between',
'conversions_to' => 'required_if:conversions,between',
]);
Here on this line 'mapping_list.*.text' => 'required|min:1' I am trying to validate this mapping_list array.
I want at least one field should be filled up but I have to fill up every element of this array.
Can you tell me is there anyting I am doing wrong?
If you want to validate that at least one field is filled, you must specify which field you want to validate. For example (in your code):
'mapping_list.*.text' => 'required|min:1',
you can change
'mapping_list.[0].text' => 'required|min:1',
or
'mapping_list.[1].text' => 'required|min:1',
That should be all you need to do. Hopefully that helps!

Filter and re-format a given multi-dimensional array (php)

I have been given a dataset by my tutor and asked to carry out the following:
// make a function
// get skus of which the figure of the average monthly sales unit is equal or greater than 350
// array in the following format:
[
'id' => 11102,
'sku' => 'TEST_3',
'alternates' => [
'asin' => [
'code' => '50',
'value' => 'JL1235',
],
'barcode' => [
'code' => '10',
'value' => 'JS160694',
],
],
'commodityCode' => '9989898889',
'price' => [
'value' => 145.99,
],
'instructions' => [
'picking' => [
'code' => 'PICK',
'value' => 'I\'VE JUST HAD AN UNHAPPY LOVE AFFAIR, SO I DON\'T SEE WHY ANYBODY ELSE SHOULD HAVE A GOOD TIME.',
],
],
'quantity' => [
'inner' => 100,
'masterCarton' => 200,
'pallet' => 300,
],
'averageMonthlyUnitSales' => 100,
'created_at' => '2022-03-13 04:14:12'
],
Example dataset is here:
$data = [
[
'id' => '9947',
'sku' => 'test_1',
'asin_code' => '50',
'asin_value' => '',
'barcode' => '10',
'barcode_value' => 'js160694',
'commodityCode' => '9989898889',
'price' => '120.50',
'picking_instruction_code' => 'PICK',
'picking_instruction_value' => '',
'qty_inner' => '120',
'qty_masterCarton' => '200',
'qty_pallet' => '1200',
'averageMonthlyUnitSales' => '750',
'created_at' => '2019-02-23T01:54:14.957299+00:00'
],
[
'id' => '10921',
'sku' => 'test_2',
'asin_code' => '50',
'asin_value' => 'bx12345',
'barcode' => '10',
'barcode_value' => 'jb170931',
'commodityCode' => '9989898889',
'price' => '20.59',
'picking_instruction_code' => 'PICK',
'picking_instruction_value' => 'It\'s only half completed, I\'m afraid',
'qty_inner' => '70',
'qty_masterCarton' => '250',
'qty_pallet' => '270',
'averageMonthlyUnitSales' => '120',
'created_at' => '2021-12-23T11:41:31.193982+00:00'
],
[
'id' => '11102',
'sku' => 'test_3',
'asin_code' => '50',
'asin_value' => 'jl1235',
'barcode' => '10',
'barcode_value' => 'js160694',
'commodityCode' => '9989898889',
'price' => '145.99',
'picking_instruction_code' => 'PICK',
'picking_instruction_value' => 'I\'ve just had an unhappy love affair, so I don\'t see why anybody else should have a good time.',
'qty_inner' => '100',
'qty_masterCarton' => '200',
'qty_pallet' => '300',
'averageMonthlyUnitSales' => '100',
'created_at' => '2022-03-13T04:14:12.11.093745 +00:00'
],
];
I can perform the first part of the assignment (filter for averageMonthlyUnitSales>350) by carrying out something like:
$filtered_array= array_filter($data, function($item){
return ($item['averageMonthlyUnitSales']>350);
});
But I am not too sure how I can go about getting a new array in the required format?
The only way I can see to simply do both is as follows.
$data = [
[
'id' => '9947',
'sku' => 'test_1',
'asin_code' => '50',
'asin_value' => '',
'barcode' => '10',
'barcode_value' => 'js160694',
'commodityCode' => '9989898889',
'price' => '120.50',
'picking_instruction_code' => 'PICK',
'picking_instruction_value' => '',
'qty_inner' => '120',
'qty_masterCarton' => '200',
'qty_pallet' => '1200',
'averageMonthlyUnitSales' => '750',
'created_at' => '2019-02-23T01:54:14.957299+00:00'
],
[
'id' => '10921',
'sku' => 'test_2',
'asin_code' => '50',
'asin_value' => 'bx12345',
'barcode' => '10',
'barcode_value' => 'jb170931',
'commodityCode' => '9989898889',
'price' => '20.59',
'picking_instruction_code' => 'PICK',
'picking_instruction_value' => 'It\'s only half completed, I\'m afraid',
'qty_inner' => '70',
'qty_masterCarton' => '250',
'qty_pallet' => '270',
'averageMonthlyUnitSales' => '120',
'created_at' => '2021-12-23T11:41:31.193982+00:00'
],
[
'id' => '11102',
'sku' => 'test_3',
'asin_code' => '50',
'asin_value' => 'jl1235',
'barcode' => '10',
'barcode_value' => 'js160694',
'commodityCode' => '9989898889',
'price' => '145.99',
'picking_instruction_code' => 'PICK',
'picking_instruction_value' => 'I\'ve just had an unhappy love affair, so I don\'t see why anybody else should have a good time.',
'qty_inner' => '100',
'qty_masterCarton' => '200',
'qty_pallet' => '300',
'averageMonthlyUnitSales' => '100',
'created_at' => '2022-03-13T04:14:12.11.093745 +00:00'
],
];
$new = [];
foreach ($data as $line){
if ( $line['averageMonthlyUnitSales'] > 350 ){
// reformat the array
$new = [
'id' => $line['id'],
'sku' => $line['sku'],
'alternates' => ['asin' => ['code'=>$line['asin_code'], 'value'=>$line['asin_value'] ],
'barcode' => ['code'=> $line['barcode'], 'value' => $line['barcode_value']]
],
'commodityCode' => $line['commodityCode'],
'price' => [ 'value' => $line['price'] ],
'instructions' => ['picking' => ['code' => $line['picking_instruction_code'], 'value'=> $line['picking_instruction_value']]
],
'quantity' =>['inner' =>$line['qty_inner'], 'masterCarton' =>$line['qty_masterCarton'], 'pallet'=>$line['qty_pallet']],
'averageMonthlyUnitSales'=>$line['averageMonthlyUnitSales'],
'created_at'=>$line['averageMonthlyUnitSales']
];
}
}
print_r($new);
RESULT
PHP 8.1.3
Array
(
[id] => 9947
[sku] => test_1
[alternates] => Array
(
[asin] => Array
(
[code] => 50
[value] =>
)
[barcode] => Array
(
[code] => 10
[value] => js160694
)
)
[commodityCode] => 9989898889
[price] => Array
(
[value] => 120.50
)
[instructions] => Array
(
[picking] => Array
(
[code] => PICK
[value] =>
)
)
[quantity] => Array
(
[inner] => 120
[masterCarton] => 200
[pallet] => 1200
)
[averageMonthlyUnitSales] => 750
[created_at] => 750
)

How to sort array based on VERY deep key value

I have this array:
array(
(int) 0 => array(
'Inscricao' => array(
'id' => '89560',
'codigo' => null,
'aluno_id' => '28065',
'turma_id' => '14377',
'estado_inscricao_id' => '13',
'nota_frequencia' => '12.00',
'nota_final' => '10.75',
'epoca_avaliacao_id' => null,
'data' => '2014-02-10',
'created' => '2015-08-31 07:12:42',
'modified' => '2015-09-02 01:31:00',
'matricula_id' => '136247',
'created_by' => null,
'modified_by' => null,
'pagamento_id' => null,
'tipo_inscricao_id' => '1',
'nota_exame_normal' => '9.50',
'nota_exame_recorrencia' => null,
'estado_inscricao' => '2',
'turma_inscricao_id' => null,
'turma_frequencia_id' => '14377'
),
'Turma' => array(
'id' => '14377',
'ano_lectivo_id' => '30',
'curso_id' => '18',
'plano_estudo_id' => '91',
'turno_id' => null,
'disciplina_id' => '394',
'capacidade_maxima' => null,
'total_aprovados' => null,
'media_turma' => null,
'estado_turma_id' => '1',
'modified' => '2015-08-31 07:02:54',
'created' => '2015-08-31 07:02:54',
'total_reprovados' => null,
'codigo' => '2011',
'ano_curricular' => '2',
'semestre_curricular' => '2',
'name' => 'Sociologia do Desporto - 2014 - Licenciatura em Ciências do Desporto - 2011',
'semestre_lectivo_id' => '66',
'sala_aula_id' => null,
'sequencia' => null,
'peso_nota_frequencia' => null,
'peso_nota_exame' => null,
'nota_minima_frequencia' => null,
'nota_minima_dispensa' => null,
'created_by' => null,
'modified_by' => null,
'pauta_path' => null,
'total_alunos' => '44',
'AnoLectivo' => array(
'id' => '30',
'codigo' => '2014',
'ano' => '2014',
'num_semestre' => null,
'data_inicio' => null,
'data_fim' => null,
'created' => '2013-10-08 05:13:51',
'modified' => '2013-10-08 05:13:51',
'regime_lectivo_id' => null
),
'Curso' => array(
'name' => 'Licenciatura em Ciências do Desporto'
),
'Turno' => array(),
'Disciplina' => array(
'id' => '394',
'name' => 'Sociologia do Desporto',
'codigo' => 'SOD',
'codigo_antigo' => null,
'created' => '1432892405',
'modified' => '1432892405',
'created_by' => '54193',
'modified_by' => null,
'unidade_organica_id' => null
)
),
'EstadoInscricao' => array(
'id' => '13',
'name' => 'Aprovado sem Exames'
),
'Matricula' => array(
'id' => '136247',
'codigo' => '',
'aluno_id' => '28065',
'curso_id' => '18',
'plano_estudo_id' => '91',
'data' => '2013-10-30',
'estado_matricula_id' => '1',
'modified' => '2015-08-31 06:55:53',
'created' => '2013-10-31 12:09:43',
'user_id' => '1',
'ano_lectivo_id' => '30',
'turno_id' => '1',
'nivel' => null,
'created_by' => '1',
'modified_by' => null,
'tipo_matricula_id' => '2',
'regime_lectivo_id' => null,
'financeiro_pagamento_id' => null,
'Aluno' => array(
'id' => '28065',
'codigo' => '20115466',
'user_id' => '28066',
'data_ingresso' => '1900-01-01',
'trabalhador' => null,
'area_trabalho_id' => null,
'instituicao_id' => null,
'curso_id' => '18',
'created' => '2011-03-02 14:15:30',
'modified' => '2015-08-31 06:55:52',
'entidade_id' => '28066',
'numero_estudante' => '20115466',
'aluno_via_admissao_id' => '13',
'numero_candidato' => null,
'ano_ingresso' => '2011',
'curso_ingresso_id' => '18',
'created_by' => null,
'modified_by' => null,
'nome_encarregado' => null,
'parentesco_encarregado' => null,
'telefone_encarregado' => null,
'telemovel_encarregado' => null,
'nome_emergencia' => null,
'telefone_emergencia' => null,
'telemovel_emergencia' => null,
'estado_aluno_id' => '1',
'plano_estudo_id' => '91',
'data_conclusao' => null,
'nota_conclusao' => null,
'certificado_nivel_anterior' => '1',
'recenseamento_militar' => '1',
'referencia_renovacao' => null,
'Entidade' => array(
'id' => '28066',
'name' => 'Elisa Luis Artur',
'nome_pai' => 'Luís Artur Vasco',
'nome_mae' => 'Jacinta António',
'foto' => '20115466.jpg',
'genero_id' => '2',
'pais_nascimento' => '152',
'cidade_morada' => null,
'bairro_morada' => null,
'caixa_postal_morada' => null,
'cidade_ferias' => null,
'cidade_nascimento' => '809',
'provincia_nascimento' => null,
'email' => '',
'telefone' => '',
'telemovel' => '825507722',
'documento_identificacao_id' => null,
'documento_identificacao_numero' => null,
'data_nascimento' => '1988-09-20',
'documento_identificacao_data_emissao' => null,
'estado_entidade_id' => null,
'created' => '2011-03-02 14:15:30',
'modified' => '2013-09-13 10:31:17',
'user_id' => '28066',
'documento_identificacao_local_emissao' => null,
'apelido' => 'Artur',
'nomes' => 'Elisa Luis ',
'created_by' => null,
'modified_by' => null,
'provincia_ferias' => null,
'telefone_ferias' => null,
'telemovel_ferias' => null,
'avenida_rua' => null,
'avenida_rua_ferias' => null,
'agregado_familiar_numero' => null,
'estado_civil' => '1',
'documento_identificacao_data_validade' => null,
'nacionalidade' => '1',
'codigo' => '41446',
'naturalidade' => null,
'nuit' => null,
'User' => array(
'password' => '*****',
'id' => '28066',
'username' => 'elisa.artur#uem.ac.mz',
'codigocartao' => '20115466',
'group_id' => '3',
'created_by' => null,
'modified_by' => null,
'ultimo_login' => null,
'codigo_activacao' => '1',
'estado_objecto_id' => '1',
'verificar_permissoes' => '0',
'created' => null,
'modified' => null,
'estado_email' => '0',
'timezone' => null,
'facebook_id' => null
)
)
)
)
),
(int) 1 => array(
'Inscricao' => array(
'id' => '92162',
'codigo' => null,
'aluno_id' => '28446',
'turma_id' => '14377',
'estado_inscricao_id' => '10',
'nota_frequencia' => '10.00',
'nota_final' => '9.75',
'epoca_avaliacao_id' => null,
'data' => '2014-02-11',
'created' => '2015-08-31 07:31:54',
'modified' => '2015-09-02 01:31:00',
'matricula_id' => '130681',
'created_by' => null,
'modified_by' => null,
'pagamento_id' => null,
'tipo_inscricao_id' => '1',
'nota_exame_normal' => '9.50',
'nota_exame_recorrencia' => null,
'estado_inscricao' => '2',
'turma_inscricao_id' => null,
'turma_frequencia_id' => '14377'
),
'Turma' => array(
'id' => '14377',
'ano_lectivo_id' => '30',
'curso_id' => '18',
'plano_estudo_id' => '91',
'turno_id' => null,
'disciplina_id' => '394',
'capacidade_maxima' => null,
'total_aprovados' => null,
'media_turma' => null,
'estado_turma_id' => '1',
'modified' => '2015-08-31 07:02:54',
'created' => '2015-08-31 07:02:54',
'total_reprovados' => null,
'codigo' => '2011',
'ano_curricular' => '2',
'semestre_curricular' => '2',
'name' => 'Sociologia do Desporto - 2014 - Licenciatura em Ciências do Desporto - 2011',
'semestre_lectivo_id' => '66',
'sala_aula_id' => null,
'sequencia' => null,
'peso_nota_frequencia' => null,
'peso_nota_exame' => null,
'nota_minima_frequencia' => null,
'nota_minima_dispensa' => null,
'created_by' => null,
'modified_by' => null,
'pauta_path' => null,
'total_alunos' => '44',
'AnoLectivo' => array(
'id' => '30',
'codigo' => '2014',
'ano' => '2014',
'num_semestre' => null,
'data_inicio' => null,
'data_fim' => null,
'created' => '2013-10-08 05:13:51',
'modified' => '2013-10-08 05:13:51',
'regime_lectivo_id' => null
),
'Curso' => array(
'name' => 'Licenciatura em Ciências do Desporto'
),
'Turno' => array(),
'Disciplina' => array(
'id' => '394',
'name' => 'Sociologia do Desporto',
'codigo' => 'SOD',
'codigo_antigo' => null,
'created' => '1432892405',
'modified' => '1432892405',
'created_by' => '54193',
'modified_by' => null,
'unidade_organica_id' => null
)
),
'EstadoInscricao' => array(
'id' => '10',
'name' => 'Reprovado'
),
'Matricula' => array(
'id' => '130681',
'codigo' => '',
'aluno_id' => '28446',
'curso_id' => '97',
'plano_estudo_id' => null,
'data' => '2013-10-17',
'estado_matricula_id' => '1',
'modified' => '2014-01-13 10:22:24',
'created' => '2013-10-17 11:18:10',
'user_id' => '1',
'ano_lectivo_id' => '30',
'turno_id' => '2',
'nivel' => null,
'created_by' => '1',
'modified_by' => null,
'tipo_matricula_id' => '2',
'regime_lectivo_id' => null,
'financeiro_pagamento_id' => null,
'Aluno' => array(
'id' => '28446',
'codigo' => '20116158',
'user_id' => '28447',
'data_ingresso' => '1900-01-01',
'trabalhador' => null,
'area_trabalho_id' => null,
'instituicao_id' => null,
'curso_id' => '97',
'created' => '2011-03-25 10:07:04',
'modified' => '2013-06-16 22:17:58',
'entidade_id' => '28447',
'numero_estudante' => '20116158',
'aluno_via_admissao_id' => '13',
'numero_candidato' => null,
'ano_ingresso' => '2012',
'curso_ingresso_id' => '18',
'created_by' => null,
'modified_by' => null,
'nome_encarregado' => null,
'parentesco_encarregado' => null,
'telefone_encarregado' => null,
'telemovel_encarregado' => null,
'nome_emergencia' => null,
'telefone_emergencia' => null,
'telemovel_emergencia' => null,
'estado_aluno_id' => '1',
'plano_estudo_id' => null,
'data_conclusao' => null,
'nota_conclusao' => null,
'certificado_nivel_anterior' => '1',
'recenseamento_militar' => '1',
'referencia_renovacao' => null,
'Entidade' => array(
'id' => '28447',
'name' => 'Paulo José Pelembe',
'nome_pai' => 'Mundau José Pelembe',
'nome_mae' => 'Rosa Fomo',
'foto' => '20116158.jpg',
'genero_id' => '1',
'pais_nascimento' => '152',
'cidade_morada' => null,
'bairro_morada' => null,
'caixa_postal_morada' => null,
'cidade_ferias' => null,
'cidade_nascimento' => '1101',
'provincia_nascimento' => null,
'email' => '',
'telefone' => '',
'telemovel' => '828352330',
'documento_identificacao_id' => null,
'documento_identificacao_numero' => null,
'data_nascimento' => '1976-12-17',
'documento_identificacao_data_emissao' => null,
'estado_entidade_id' => null,
'created' => '2011-03-25 10:07:03',
'modified' => '2013-09-13 10:37:47',
'user_id' => '28447',
'documento_identificacao_local_emissao' => null,
'apelido' => 'Pelembe',
'nomes' => 'Paulo José ',
'created_by' => null,
'modified_by' => null,
'provincia_ferias' => null,
'telefone_ferias' => null,
'telemovel_ferias' => null,
'avenida_rua' => null,
'avenida_rua_ferias' => null,
'agregado_familiar_numero' => null,
'estado_civil' => '1',
'documento_identificacao_data_validade' => null,
'nacionalidade' => '1',
'codigo' => '41832',
'naturalidade' => null,
'nuit' => null,
'User' => array(
'password' => '*****',
'id' => '28447',
'username' => 'paulo.pelembe#uem.ac.mz',
'codigocartao' => '20116158',
'group_id' => '3',
'created_by' => null,
'modified_by' => null,
'ultimo_login' => null,
'codigo_activacao' => '1',
'estado_objecto_id' => '1',
'verificar_permissoes' => '0',
'created' => null,
'modified' => null,
'estado_email' => '0',
'timezone' => null,
'facebook_id' => null
)
)
)
)
),
(int) 2 => array(
'Inscricao' => array(
'id' => '92200',
'codigo' => null,
'aluno_id' => '28504',
'turma_id' => '14377',
'estado_inscricao_id' => '13',
'nota_frequencia' => '10.00',
'nota_final' => '10.25',
'epoca_avaliacao_id' => null,
'data' => '2014-02-10',
'created' => '2015-08-31 07:32:17',
'modified' => '2015-09-02 01:31:00',
'matricula_id' => '141228',
'created_by' => null,
'modified_by' => null,
'pagamento_id' => null,
'tipo_inscricao_id' => '1',
'nota_exame_normal' => '8.50',
'nota_exame_recorrencia' => '10.50',
'estado_inscricao' => '2',
'turma_inscricao_id' => null,
'turma_frequencia_id' => '14377'
),
'Turma' => array(
'id' => '14377',
'ano_lectivo_id' => '30',
'curso_id' => '18',
'plano_estudo_id' => '91',
'turno_id' => null,
'disciplina_id' => '394',
'capacidade_maxima' => null,
'total_aprovados' => null,
'media_turma' => null,
'estado_turma_id' => '1',
'modified' => '2015-08-31 07:02:54',
'created' => '2015-08-31 07:02:54',
'total_reprovados' => null,
'codigo' => '2011',
'ano_curricular' => '2',
'semestre_curricular' => '2',
'name' => 'Sociologia do Desporto - 2014 - Licenciatura em Ciências do Desporto - 2011',
'semestre_lectivo_id' => '66',
'sala_aula_id' => null,
'sequencia' => null,
'peso_nota_frequencia' => null,
'peso_nota_exame' => null,
'nota_minima_frequencia' => null,
'nota_minima_dispensa' => null,
'created_by' => null,
'modified_by' => null,
'pauta_path' => null,
'total_alunos' => '44',
'AnoLectivo' => array(
'id' => '30',
'codigo' => '2014',
'ano' => '2014',
'num_semestre' => null,
'data_inicio' => null,
'data_fim' => null,
'created' => '2013-10-08 05:13:51',
'modified' => '2013-10-08 05:13:51',
'regime_lectivo_id' => null
),
'Curso' => array(
'name' => 'Licenciatura em Ciências do Desporto'
),
'Turno' => array(),
'Disciplina' => array(
'id' => '394',
'name' => 'Sociologia do Desporto',
'codigo' => 'SOD',
'codigo_antigo' => null,
'created' => '1432892405',
'modified' => '1432892405',
'created_by' => '54193',
'modified_by' => null,
'unidade_organica_id' => null
)
),
'EstadoInscricao' => array(
'id' => '13',
'name' => 'Aprovado sem Exames'
),
'Matricula' => array(
'id' => '141228',
'codigo' => '',
'aluno_id' => '28504',
'curso_id' => '18',
'plano_estudo_id' => '91',
'data' => '2013-10-31',
'estado_matricula_id' => '1',
'modified' => '2015-08-31 06:56:21',
'created' => '2013-11-01 07:56:44',
'user_id' => '1',
'ano_lectivo_id' => '30',
'turno_id' => '1',
'nivel' => null,
'created_by' => '1',
'modified_by' => null,
'tipo_matricula_id' => '2',
'regime_lectivo_id' => null,
'financeiro_pagamento_id' => null,
'Aluno' => array(
'id' => '28504',
'codigo' => '20116434',
'user_id' => '28505',
'data_ingresso' => '1900-01-01',
'trabalhador' => null,
'area_trabalho_id' => null,
'instituicao_id' => null,
'curso_id' => '18',
'created' => '2011-03-28 12:12:43',
'modified' => '2015-08-31 06:56:21',
'entidade_id' => '28505',
'numero_estudante' => '20116434',
'aluno_via_admissao_id' => '13',
'numero_candidato' => null,
'ano_ingresso' => '2011',
'curso_ingresso_id' => '18',
'created_by' => null,
'modified_by' => null,
'nome_encarregado' => null,
'parentesco_encarregado' => null,
'telefone_encarregado' => null,
'telemovel_encarregado' => null,
'nome_emergencia' => null,
'telefone_emergencia' => null,
'telemovel_emergencia' => null,
'estado_aluno_id' => '1',
'plano_estudo_id' => '91',
'data_conclusao' => null,
'nota_conclusao' => null,
'certificado_nivel_anterior' => '1',
'recenseamento_militar' => '1',
'referencia_renovacao' => null,
'Entidade' => array(
'id' => '28505',
'name' => 'Lina Mário Matola',
'nome_pai' => 'Mário Augusto Matola',
'nome_mae' => 'Lina Albino Manjate',
'foto' => '20116434.jpg',
'genero_id' => '2',
'pais_nascimento' => '152',
'cidade_morada' => null,
'bairro_morada' => null,
'caixa_postal_morada' => null,
'cidade_ferias' => null,
'cidade_nascimento' => '1101',
'provincia_nascimento' => null,
'email' => 'linamario16#yahoo.com.br ',
'telefone' => '',
'telemovel' => '828322450',
'documento_identificacao_id' => null,
'documento_identificacao_numero' => null,
'data_nascimento' => '1988-04-13',
'documento_identificacao_data_emissao' => null,
'estado_entidade_id' => null,
'created' => '2011-03-28 12:12:42',
'modified' => '2013-09-13 10:38:41',
'user_id' => '28505',
'documento_identificacao_local_emissao' => null,
'apelido' => 'Matola',
'nomes' => 'Lina Mário',
'created_by' => null,
'modified_by' => null,
'provincia_ferias' => null,
'telefone_ferias' => null,
'telemovel_ferias' => null,
'avenida_rua' => null,
'avenida_rua_ferias' => null,
'agregado_familiar_numero' => null,
'estado_civil' => '1',
'documento_identificacao_data_validade' => null,
'nacionalidade' => '1',
'codigo' => '41891',
'naturalidade' => null,
'nuit' => null,
'User' => array(
'password' => '*****',
'id' => '28505',
'username' => 'lina.matola#uem.ac.mz',
'codigocartao' => '20116434',
'group_id' => '3',
'created_by' => null,
'modified_by' => null,
'ultimo_login' => null,
'codigo_activacao' => '1',
'estado_objecto_id' => '1',
'verificar_permissoes' => '0',
'created' => null,
'modified' => null,
'estado_email' => '0',
'timezone' => null,
'facebook_id' => null
)
)
)
)
),
(int) 3 => array(
and I want to sort this based on key "apelido". What is the best way to do this in PHP?
Note: the Key apelido is in [0]['Matricula']['Aluno']['Entidade']['apelido'].
NOTE 2: This is a result of CakePHP find with Containable. Is there a way that cake could sort it during find?
Use Hash::sort(), it accepts a path in Hash path syntax format, allowing to specify deeply nested paths.
$sorted = Hash::sort($data, '{n}.Matricula.Aluno.Entidade.apelido');
Further arguments define the sort order, and the sort type, see Cookbook > Core Libraries > Utilities > Hash > Hash::sort() for more information.
If you want to have this being returned sorted by the find call, you could for example modify the results in the Model::afterFind() callback, or in a custom finder, see
Cookbook > Models > Callback Methods > afterFind
Cookbook > Models > Retrieving Your Data > Creating custom find types

cakephp manually building arrays

I have a relationship where a quote habtm applicants. I am trying to get a quote to save with multiple applicants at once. I already have an array of the applicants I need but I don't know how to format that array to get it to save when I insert it into the quote array.
The applicant array looks like this:
array(
(int) 0 => array(
'Applicant' => array(
'id' => '436',
'clientcase_id' => '66',
'archive_id' => '1',
'birthdate' => '2013-09-21 01:41:00',
'title' => '',
'first_name' => 'george',
'middle_name' => 'a',
'surname' => 'summerlane',
'email' => 'email#q.com',
'landline_number' => '88465120.',
'mobile_number' => '',
'applicant_type' => '',
'created' => '2013-09-21 01:43:10',
'modified' => '2013-09-21 01:43:10'
)
),
(int) 1 => array(
'Applicant' => array(
'id' => '435',
'clientcase_id' => '66',
'archive_id' => '1',
'birthdate' => '2013-09-21 01:41:00',
'title' => '',
'first_name' => 'mary',
'middle_name' => 's',
'surname' => 'amnn',
'email' => 'some#this.cin',
'landline_number' => '465132',
'mobile_number' => '',
'applicant_type' => '',
'created' => '2013-09-21 01:41:48',
'modified' => '2013-09-21 01:41:48'
)
),
(int) 2 => array(
'Applicant' => array(
'id' => '66',
'clientcase_id' => '66',
'archive_id' => '1',
'birthdate' => null,
'title' => null,
'first_name' => 'Tania',
'middle_name' => '',
'surname' => 'Humphreys',
'email' => 'purple67#me.com',
'landline_number' => null,
'mobile_number' => '0438854355',
'applicant_type' => 'Main applicant',
'created' => '2012-10-29 00:00:00',
'modified' => '2012-10-21 00:00:00'
)
)
)
I need one that looks like this:
array(
'Applicants' => array(
'id' => 435,
'id' => 436,
'id' => 66
)
)
How might I go about doing this?
Or is there a better way?
When I save a quote the array looks like this:
array(
'QuoteButton' => 'Submit',
'Quote' => array(
'date' => array(
'day' => '13',
'month' => '10',
'year' => '2013'
),
'description' => '',
'quote_accepted' => '0',
'research_accepted' => '0',
'cc_accepted' => '0',
'pesel_accepted' => '0',
'setfees_accepted' => '0',
'total' => '0'
),
'Applicant' => array(
'id' => '66'
),
How do I insert more than one applicant into the array?
An array can't have the same id, but can crate another array like this:
$datas = array(
(int) 0 => array(
'Applicant' => array(
'id' => '436',
'clientcase_id' => '66',
'archive_id' => '1',
'birthdate' => '2013-09-21 01:41:00',
'title' => '',
'first_name' => 'george',
'middle_name' => 'a',
'surname' => 'summerlane',
'email' => 'email#q.com',
'landline_number' => '88465120.',
'mobile_number' => '',
'applicant_type' => '',
'created' => '2013-09-21 01:43:10',
'modified' => '2013-09-21 01:43:10'
)
),
(int) 1 => array(
'Applicant' => array(
'id' => '435',
'clientcase_id' => '66',
'archive_id' => '1',
'birthdate' => '2013-09-21 01:41:00',
'title' => '',
'first_name' => 'mary',
'middle_name' => 's',
'surname' => 'amnn',
'email' => 'some#this.cin',
'landline_number' => '465132',
'mobile_number' => '',
'applicant_type' => '',
'created' => '2013-09-21 01:41:48',
'modified' => '2013-09-21 01:41:48'
)
),
(int) 2 => array(
'Applicant' => array(
'id' => '66',
'clientcase_id' => '66',
'archive_id' => '1',
'birthdate' => null,
'title' => null,
'first_name' => 'Tania',
'middle_name' => '',
'surname' => 'Humphreys',
'email' => 'purple67#me.com',
'landline_number' => null,
'mobile_number' => '0438854355',
'applicant_type' => 'Main applicant',
'created' => '2012-10-29 00:00:00',
'modified' => '2012-10-21 00:00:00'
)
)
);
$ids = array();
foreach($datas as $data => $applicants) {
$ids[] = $applicants['Applicant']['id'];
}
print_r($ids);
Output:
Array ( [0] => 436 [1] => 435 [2] => 66 )
How to use the ids? Like this:
foreach($ids as $key => $id) {
// do whatever you want with the applicant id
}
like tttony pointed out, array indexes need to be unique so i would:
$ids = array();
foreach($array as $applicant)
$ids[$applicant['Applicant']['id']] = null;
which will output:
Array
(
[436] =>
[435] =>
[66] =>
)
now id is key to $ids array...you could add something else as value rather than null

PHP and PayPal IPN array

I am getting PayPal's IPN in array form like this:
$ipn = array(
'mc_gross' => '15.50',
'protection_eligibility' => 'Eligible',
'address_status' => 'confirmed',
'item_number1' => '1',
'tax' => '0.00',
'item_number2' => '2',
'payer_id' => 'XXXXXXXXXXXXX',
'address_street' => '1 Main St',
'payment_date' => '02:41:18 Nov 23, 2011 PST',
'payment_status' => 'Completed',
'charset' => 'windows-1252',
'address_zip' => '95131',
'mc_shipping' => '0.00',
'mc_handling' => '0.00',
'first_name' => 'Test',
'mc_fee' => '0.75',
'address_country_code' => 'US',
'address_name' => 'Test User',
'custom' => '',
'payer_status' => 'verified',
'business' => 'receiver#example.com',
'address_country' => 'United States',
'num_cart_items' => '2',
'mc_handling1' => '0.00',
'mc_handling2' => '0.00',
'address_city' => 'San Jose',
'payer_email' => 'payer#example.com',
'mc_shipping1' => '0.00',
'mc_shipping2' => '0.00',
'txn_id' => '8RE82733S8684874F',
'payment_type' => 'instant',
'last_name' => 'User',
'address_state' => 'CA',
'item_name1' => 'trilogy2',
'receiver_email' => 'receiver#example.com',
'item_name2' => 'trilogy1',
'payment_fee' => '0.75',
'quantity1' => '1',
'quantity2' => '1',
'receiver_id' => 'XXXXXXXXXXXXX',
'txn_type' => 'cart',
'mc_gross_1' => '5.55',
'mc_currency' => 'USD',
'mc_gross_2' => '9.95',
'residence_country' => 'US',
'transaction_subject' => 'Shopping Carttrilogy2trilogy1',
'payment_gross' => '15.50',
'' => ''
);
In this case customer has ordered only 2 items: 'item_name1' and 'item_name2'
Obviously, a customer can order X number of products and PayPal will include an 'item_nameX' in the notification data. Is there a way to go through the array and extract all names and assign them to variables so I will have something like:
$ordered_item1 = $ipn['item_name1'];
$ordered_item2 = $ipn['item_name2'];
...
$ordered_itemXYZ = $ipn['item_nameXYZ'];
Thanks for any help.
If you have data named with a prefix followed by a count, you should be using an array, not separate variables. To fill an array with the item information:
foreach ($ipn as $key => $value) {
if (preg_match('/(?P<field>[a-z]+)_?(?P<i>\d+)/', $key, $parts)) {
$ordered_items[(int) $parts['i']][$parts['field']] = $value;
}
}

Categories