I'm trying to convert some array values (group then actually), but I don't know how to do that.
I have something like this:
[
{
"nsr": "000086310",
"type": "3",
"date": "2015-07-18",
"time": "00:06",
"pis": "12138790985"
},
{
"nsr": "000086313",
"type": "3",
"date": "2015-07-18",
"time": "00:33",
"pis": "16073736879"
},
{
"nsr": "000086316",
"type": "3",
"date": "2015-07-18",
"time": "00:58",
"pis": "16634402451"
},
{
"nsr": "000086316",
"type": "3",
"date": "2015-07-19",
"time": "00:58",
"pis": "98127981729"
},
{
"nsr": "000086316",
"type": "3",
"date": "2015-07-19",
"time": "00:58",
"pis": "12398712938"
}
]
And I want to convert to this:
[
"date" : "2015-07-18",
"pis" : [
"12138790985",
"16073736879",
"16634402451"
]
],
[
"date" : "2015-07-19",
"pis" : [
"98127981729",
"12398712938"
]
]
I tried to do something like this:
public function index()
{
$this->setTxtData('../../txt_files/CAP 3 18 07 2015 FABRICA.txt');
$txtdata = $this->getTxtData();
$dataToCompare = array();
foreach($txtdata as $ponto){
$time = $ponto['time'];
$date = $ponto['date'];
$pis = $ponto['pis'];
// $dataToCompare = array();
// if(strpos($ponto['pis'], '00000000000') === false){
// $pis_temp[][''] = $ponto['pis'];
// }
if(isset($dataToCompare)){
foreach($dataToCompare as $dateToSet){
if($dateToSet['data'] == $date){
$dateToSet['pis'][] = $pis;
}
else{
$dateToSet['data'] = $date;
$dateToSet['pis'][] = $pis;
}
}
}
else{
$dataToCompare = array(
[
'data' => $date,
'pis' => array($pis)
]
);
}
$funcionario_id = DB::table('funcionario')
->select('id')
->where('pis_pasep', '=', $pis)
->pluck('id');
if($funcionario_id !== null){
$validate = DB::table('horas_trabalho')
->select('id')
->where('hora', '=', $time)
->where('data', '=', $date)
->where('funcionario_id', '=', $funcionario_id)
->pluck('id');
if($validate === null){
DB::table('horas_trabalho')
->insert([
'hora' => $time,
'data' => $date,
'funcionario_id' => $funcionario_id
]);
}
}
}
//-------------------------------------Lógica para faltas-----------------------------------
/**
* Pega o pis
*/
$db_all_funcionarios = DB::table('funcionario')
->select('pis_pasep')
->where('pis_pasep', '!=', 0)
->get();
foreach($db_all_funcionarios as $pis){
if(strpos($pis->pis_pasep, '00000000000') !== true){
$global_pis[] = $pis->pis_pasep;
}
}
// $faltantes = array_diff($pis_temp, $global_pis);
// foreach($faltantes as $faltante){
// DB::table('falta')
// ->insert([
// 'data' => date('2015-07-16')
// ]);
// }
// $ponto_db[] = DB::table('horas_trabalho')
// ->join('funcionario', 'horas_trabalho.funcionario_id', '=', 'funcionario.id')
// ->select('funcionario.nome', 'horas_trabalho.hora', 'horas_trabalho.data')
// ->get();
return $txtdata;
}
I see the date in your filename and think you want group all entities at all:
$dataToCompare = array(
'date' => $txtData[0]['date'],
'pis' => array_map(function($el){return $el['pis'];}, $txtData)
);
For multiple dates:
$hash = array();
foreach ($txtData as $entity) {
if (!isset($hash[$entity['date']])) $hash[$entity['date']] = array();
$hash[$entity['date']][] = $entity['pis'];
}
$result = array();
foreach($hash as $date=>$pis) {
$result[] = array('date'=>$date, 'pis'=>$pis);
}
It might be a little sloppy, but it does the job. Or either way, it works as you wanted in the example:
<?php
$array = array(
0 => array(
"nsr" => "000086310",
"type" => "3",
"date" => "2015-07-18",
"time" => "00:06",
"pis" => "12138790985"
),
1 => array(
"nsr" => "000086313",
"type" => "3",
"date" => "2015-07-18",
"time" => "00:33",
"pis" => "16073736879"
),
2 => array(
"nsr" => "000086316",
"type" => "3",
"date" => "2015-07-18",
"time" => "00:58",
"pis" => "16634402451"
)
);
$newarray = array();
$pis = array();
foreach($array as $part){
array_push($pis,$part['pis']);
$newarray = array(
"date" => $part['date'],
"pis" => $pis
);
}
var_dump($newarray);
?>
$array = json_decode($str, true);
// make array date => pis
$tmp = array();
foreach ($array as $item) {
if (!isset($tmp[$item['date']])) $tmp[$item['date']]['pis'] = array();
$tmp[$item['date']]['pis'][] = $item['pis'];
}
// Than move date from key to item
$result = array();
foreach($tmp as $k=>$v)
$result[] = array('date' => $k, 'pis' => $v['pis']);
print_r($result);
Related
I am using below php code for creating dynamic queries in mongo db like
..........
if ($this->programId != "") {
$query['classId'] = new MongoDB\BSON\ObjectID($this->programId);
}
......
$transportArrayCondition1 = ['transport_details' => ['$size' => 0]];
$transportArrayCondition2 = ['transport_details' => ['$elemMatch' => [
'$or' => [
['status' => ['$eq' => 'Requested']],
['status' => ['$eq' => 'Active']],
],
"approval_status" => "approved",
"allotable" => "yes",
]]];
$conditionToApply = '$or';
if($this->routeId != "")
{
$transportArrayCondition1 = ['transport_details' => ['$gt' => ['$size' => 0]]];
$transportArrayCondition2 = ['transport_details' => ['$elemMatch' => [
'$or' => [
['status' => ['$eq' => 'Requested']],
['status' => ['$eq' => 'Active']],
],
"approval_status" => "approved",
"allotable" => "yes",
"route_id" => new MongoDB\BSON\ObjectID($this->routeId)
]]];
$conditionToApply = '$and';
}
if ($this->stopId != "")
{
$transportArrayCondition1 = ['transport_details' => ['$gt' => ['$size' => 0]]];
$transportArrayCondition2 = ['transport_details' => ['$elemMatch' => [
'$or' => [
['status' => ['$eq' => 'Requested']],
['status' => ['$eq' => 'Active']],
],
"approval_status" => "approved",
"allotable" => "yes",
"route_id" => new MongoDB\BSON\ObjectID($this->routeId),
"stop_id" => $this->stopId
]]];
$conditionToApply = '$and';
}
$query[$conditionToApply] = [$transportArrayCondition1, $transportArrayCondition2];
if ($this->name != "") {
$nameArray = ['$or' => [
['fullName' => new MongoDB\BSON\Regex('^' . $this->name, 'i')],
['firstLastName' => new MongoDB\BSON\Regex('^' . $this->name, 'i')],
['registration_temp_perm_no' => new MongoDB\BSON\Regex('^' . $this->name, 'i')],
]];
array_push($query,$nameArray);
}
Actually, I have put conditions in $query variables for MongoDB commands. I am failing to create condition in if '$this->name != "" ' part of the query. I am getting $query formed like
{
"0": {
"$or": [
{
"fullName": {
"$regex": "^Vika",
"$options": "i"
}
},
{
"firstLastName": {
"$regex": "^Vika",
"$options": "i"
}
},
{
"registration_temp_perm_no": {
"$regex": "^Vika",
"$options": "i"
}
}
]
},
"schoolId": {
"$oid": "5f7aba204c610000670026d2"
},
"status": "Active",
"activeAcademicyearId": {
"$oid": "5f7abaa54c61000067002738"
},
"$or": [
{
"transport_details": {
"$size": 0
}
},
{
"transport_details": {
"$elemMatch": {
"$or": [
{
"status": {
"$eq": "Requested"
}
},
{
"status": {
"$eq": "Active"
}
}
],
"approval_status": "approved",
"allotable": "yes"
}
}
}
]
}
What I actually want is
{
"$or": [
{
"fullName": {
"$regex": "^Vika",
"$options": "i"
}
},
{
"firstLastName": {
"$regex": "^Vika",
"$options": "i"
}
},
{
"registration_temp_perm_no": {
"$regex": "^Vika",
"$options": "i"
}
}
]
"schoolId": {
"$oid": "5f7aba204c610000670026d2"
},
"status": "Active",
"activeAcademicyearId": {
............
I want array_push should add condition in $query like "$or": [...]. It should not add condition like "0": {"$or": [... ]}, I have tried a lot of things since morning but could not find any solution. Kindly help !!!
Since $query is associated array like structure and it already contains $or key in which you want to add the element you may need to update it as below.
Change $nameArray as below
$nameArray = [
['fullName' => new MongoDB\BSON\Regex('^' . $this->name, 'i')],
['firstLastName' => new MongoDB\BSON\Regex('^' . $this->name, 'i')],
['registration_temp_perm_no' => new MongoDB\BSON\Regex('^' . $this->name, 'i')],
];
array_push add elements add the end of the array
If you want to merge with existing $or values then we can use array_merge to merge both as array and then reassign it to existing $or key in $query
$query['$or'] = array_merge($nameArray, $query['$or']);
Or
$query['$or'] = $nameArray + $query['$or'];
If you want to replace then you can just reassign the changed $nameArray variable to $query['$or']
$query['$or'] = $nameArray;
Help me how to add data to the array correctly.Below I give an example of what I want to get in the end after printing the array
$arr = [];
$data = [
"offer_id" => (string)777380,
"price" => (string)5633
];
array_push($arr, $data);
print_r(json_encode($arr));
I want to get this
{
"prices": [
{
"offer_id": "777380",
"price": "5633"
},
{
"offer_id": "777380",
"price": "5633"
}
]
}
You can use like below:
$arr['prices']=[];
$data = [
"offer_id" => (string)777380,
"price" => (string)5633
];
array_push($arr['prices'], $data);
$data = [
"offer_id" => (string)777380,
"price" => (string)5633
];
array_push($arr['prices'], $data);
print_r(json_encode($arr));
$arr = [];
$data = [
"offer_id" => (string)777380,
"price" => (string)5633
];
$arr['prices'][] = $data;
print_r(json_encode($arr));
I'm making an API for getting some data. My API gives object data like given, given object I wanted to format some data inside object:
{
"data": [
{
"productId": 55,
"productTitle": "Test product",
"variation": {
"Color": "Red",
"Size": "XS",
"din": "10190537",
"product_id": 55,
"name": [
"Color",
"Size"
],
"value": [
"Red",
"XS"
]
},
"din": "10190537",
"markets": [
{
"id": 11,
"name": "paytmmall",
"displayName": "PayTm Mall",
"identifierName": "Product_Id"
}
]
}
]
}
In this object I want data like given
{
"data": [
{
"productId": 55,
"productTitle": "this is test from hariom",
"variation": {
"Color": "Red",
"Size": "XS",
"din": "10190537",
"product_id": 55,
"variationTypes": [
{
"name": "Color",
"value": "Red"
},
{
"name": "Size",
"value": "XS"
}
],
},
"din": "10190537",
"markets": [
{
"id": 11,
"name": "paytmmall",
"displayName": "PayTm Mall",
"identifierName": "Product_Id"
}
]
}
]
}
Here Is my Controller Name
public function MarketMapping(Request $request)
{
$sellerId = Auth::guard('seller-api')->user();
$page = $request->has('pageNumber') ? $request->get('pageNumber') : 1;
$limit = $request->has('perPage') ? $request->get('perPage') : 10;
$variationFromInvTbl = ProductInventory::select('Color', 'Size', 'din', 'product_id')->where('seller_id', $sellerId->id)->where('status', 'active')->limit($limit)->offset(($page - 1) * $limit)->get();
$dataArray = array();
foreach($variationFromInvTbl as $key => $varitionValue)
{
$prodtsFromLivetbl = ProductsLive::select('productTitle', 'product_id')->where('product_id', $varitionValue->product_id)->get();
foreach ($prodtsFromLivetbl as $key => $value)
{
$marketChannelData = DB::table('market_channels')
->join('sellers_market_channels', 'market_channels.name', '=', 'sellers_market_channels.key')
//->join('market_product_mappings', 'market_channels.id', '=', 'market_product_mappings.market_id')
->select('market_channels.id','market_channels.name', 'market_channels.displayName','market_channels.identifierName') //'market_product_mappings.identifierValue'
->where('sellers_market_channels.seller_id', $sellerId->id)
->where('sellers_market_channels.value', 1)
->get();
$maketProductMap = MarketProductMapping::where('seller_id', $sellerId->id)->where('product_id', $varitionValue->product_id)->where('din', $varitionValue->din)->pluck('identifierValue');
if (count($maketProductMap))
{
$marketChannelData[$key]->value = $maketProductMap[0];
}
$varitionValue['name']= array_keys($varitionValue->only(['Color', 'Size']));
$varitionValue['value'] = array_values($varitionValue->only(['Color', 'Size']));
$dataObject = ((object)[
"productId" => $value->product_id,
"productTitle" => $value->productTitle,
"variation" => $varitionValue,
"din" => $varitionValue['din'],
"markets" => $marketChannelData
]);
array_push($dataArray,$dataObject);
}
}
if($variationFromInvTbl)
{
$response['success'] = true;
$response["page"] = $page;
$response["itemPerPage"] = $limit;
$response["totalRecords"] = $this->CountMarketMapping($page, $limit, $sellerId->id);
$response['data'] = $dataArray;
return response()->json($response, 200);
}else{
$response['success'] = false;
$response['data'] = $prodtsFromLivetbl;
return response()->json($response, 409);
}
}
You are using laravel's only() method which returns an associative array.
You wish to convert each key-value pair into a subarray containing two associative elements -- the original key will be the value of the name element
and the original value will be the value of the value element.
By passing the original array keys and array values into array_map(), you can iterate them both synchronously.
compact() is a perfect native function to create the desired associative subarrays from the iterated parameters.
Code: (Demo)
$variations = $varitionValue->only(['Color', 'Size']);
$dataObject = (object)[
// ... your other data
'variations' => array_map(
function($name, $value) {
return compact(['name', 'value']);
},
array_keys($variations),
$variations
),
// ...your other data
];
var_export($dataObject);
Output:
(object) array(
'variations' =>
array (
0 =>
array (
'name' => 'Color',
'value' => 'Red',
),
1 =>
array (
'name' => 'Size',
'value' => 'XS',
),
),
)
This script will help you
<?php
$data = [
"variation" => [
[
"Color" => "Red",
"Size" => "XS",
"din" => "10190537",
"product_id" => 55,
"name" => [
"0" => "Color",
"1" => "Size"
],
"value" => [
"0" => "Red",
"1" => "XS"
]
]
]
];
for ($i=0; $i < count($data["variation"]); $i++) {
$data["variation"][$i]["data"]["name"] = $data["variation"][$i]["name"];
$data["variation"][$i]["data"]["value"] = $data["variation"][$i]["value"];
unset($data["variation"][$i]["name"]);
unset($data["variation"][$i]["value"]);
}
print_r($data);
output
Array
(
[variation] => Array
(
[0] => Array
(
[Color] => Red
[Size] => XS
[din] => 10190537
[product_id] => 55
[data] => Array
(
[name] => Array
(
[0] => Color
[1] => Size
)
[value] => Array
(
[0] => Red
[1] => XS
)
)
)
)
)
I'm trying to input some JSON data in a table between Laravel, but i'm receiving the Array to string Conersion.
This is my JSON:
{
"data": [
{
"client_id": "3",
"vehicle_id": "3",
"cart1_id": "3",
"cart2_id": "3",
"driver1_id": "3",
"driver2_id": "3",
"shipper_id": "3",
"transportationtype_id": "1",
"startdatetime": "2018-10-10 11:00:00",
"enddatetime": "2018-10-10 18:00:00",
"consultnumber": "3",
"consultvalidity": "2018-10-20",
"escorted": "1",
"escortcompany": "Teste",
"escortplate": "ABC-1234",
"escorttrackingtecnology": "1",
"escorttrackingserial": "123",
"contactname": "José",
"contacttel": "17-997157517",
"decoy": "0",
"decoytrackingtecnology": "1",
"decoyserial": "9999",
"decoysite": "www",
"decoylogin": "123",
"decoypassword": "bacd",
"charged": "1",
"charge": [
{
"description": "Teste Carga 1",
"nf": "1234",
"amount": "1000.00"
},
{
"description": "Teste Carga 2",
"nf": "4321",
"amount": "2000.00"
}
]
}
]
}
And this is my Controller:
public function storeapi(Request $request)
{
$array = $request->all();
$insertedIds = [];
foreach ($array['data'] as $row) {
$validator = Validator::make($array['data'], [
$row['vehicle_id'] => 'required',
$row['driver1_id'] => 'required',
]);
if($validator->fails()) {
return response()->json([
'message' => 'Validation Failed',
'errors' => $validator->errors()->all()
], 422);
}
$newSm = Sm::create([
'client_id' => $row['client_id'],
'veiculo_id' => $row['vehicle_id'],
'carreta1_id' => $row['cart1_id'],
'carreta2_id' => $row['cart2_id'],
'motorista1_id' => $row['driver1_id'],
'motorista2_id' => $row['driver2_id'],
'embarcador_id' => $row['shipper_id'],
'tipotransporte_id' => $row['transportationtype_id'],
'inicioprevisao' => $row['startdatetime'],
'fimprevisao' => $row['enddatetime'],
'nroliberacao' => $row['consultnumber'],
'datavigencia' => $row['consultvalidity'],
'escolta' => $row['escorted'],
'empresa' => $row['escortcompany'],
'placaescolta' => $row['escortplate'],
'tecnologia_id' => $row['escorttrackingtecnology'],
'serial' => $row['escorttrackingserial'],
'nomecontato' => $row['contactname'],
'telefonecontato' => $row['contacttel'],
'isca' => $row['decoy'],
'tecnologiaisca_id' => $row['decoytrackingtecnology'],
'serialisca' => $row['decoyserial'],
'siteisca' => $row['decoysite'],
'login' => $row['decoylogin'],
'senha' => $row['decoypassword'],
'status_id' => "1"
]);
$insertedIds[] = $newSm->id;
foreach ($row['charge'] as $key => $charge){
$carga = new Carga();
$carga->descricao = $charge['description'];
$carga->nf = $charge['nf'];
$carga->valor = $charge['amount'];
$carga->sm_id = $insertedIds;
$carga->save();
}
return response()->json($insertedIds, 201);
}
}
And this is the returned error:
Illuminate \ Database \ QueryException
Array to string conversion (SQL: insert into cargas (descricao, nf, valor, sm_id, updated_at, created_at) values (Teste Carga 1, 1234, 1000.00, 89, 2018-10-11 16:55:57, 2018-10-11 16:55:57))
You have $carga->sm_id = $insertedIds; which is writing an array to the database. You cannot do this. Either store a single sm_id, or serialize the array using serialize($carga->sm_id), or normalize your database if you need multiple IDs for this row, and create a second table and use a foreign key.
EDIT:
Checking your code, you probably want this instead:
$carga->sm_id = $newSm->id;
$carga->save();
...
Use this:
$insertedIds[] = $newSm->id;
foreach ($row['charge'] as $key => $charge){
$carga = new Carga();
$carga->descricao = $charge['description'];
$carga->nf = $charge['nf'];
$carga->valor = $charge['amount'];
$carga->sm_id = $newSm->id;
$carga->save();
}
as $newSm->id is initializing in array $insertedIds[] and $carga->sm_id in database table Cargas may be of type integer or string
I run queries on 3 tables and I'm trying to format results into a nested array. It's the inner array thats got me stumped. sizes array should be in the beer array object but its outside of it. Any help appreciated.
JSON
{
"brewerId": "41",
"brewerName": "Prancing Pony Brewing",
"beers": [
{
"beerid": "816",
"productName": "Prancing Pony Amber Ale",
"ibu": "18.00",
"abv": "5.00",
"style": "Amber Ale"
},
{
"beerid": "817",
"productName": "Prancing Pony Copper Ale",
"ibu": "25.00",
"abv": "5.80",
"style": "Indian Pale Ale"
},
{
"beerid": "837",
"productName": "Prancing Pony Pale Ale",
"ibu": "37.00",
"abv": "5.50",
"style": "Pale Ale"
},
{
"beerid": "838",
"productName": "Prancing Pony India Red Ale",
"ibu": "60.00",
"abv": "7.90",
"style": "Indian Pale Ale"
}
],
"sizes": [
{
"beerId": "816",
"size": "330ml Bottle"
},
{
"beerId": "816",
"size": "330ml Can"
},
{
"beerId": "837",
"size": "345ml Can"
},
{
"beerId": "837",
"size": "375ml Bottle"
}
]
},
PHP
$result = $func->getBrewers();
$json_response = array();
while ($row = mysqli_fetch_array($result))
{
$row_array = array();
$row_array['brewerId'] = $row['brewerId'];
$row_array['brewerName'] = $row['brewerName'];
$row_array['beers'] = array();
$brewer_pk = $row['brewerId'];
$beer_qry = $func->getBeers($brewer_pk);
while ($beer_fet = mysqli_fetch_array($beer_qry))
{
$row_array['beers'][] = array(
'beerid' => $beer_fet['beerid'],
'productName' => $beer_fet['productName'],
'ibu' => $beer_fet['ibu'],
'abv' => $beer_fet['abv'],
'notes' => $beer_fet['notes'],
'style' => $beer_fet['style'],
);
$beer_pk = $beer_fet['beerid'];
$size_qry = $func->getSizes($beer_pk);
while ($size_fet = mysqli_fetch_array($size_qry))
{
$row_array['sizes'][] = array(
'beerId' => $size_fet['beerId'],
'size' => $size_fet['size'],
);
}
}
array_push($json_response, $row_array);
}
echo json_encode($json_response);
It seems you misindented at some point and just went wrong from that point on.
$result = $func->getBrewers();
$json_response = array();
while ($row = mysqli_fetch_array($result))
{
$row_array = array(
'brewerId' => $row['brewerId'],
'brewerName' => $row['brewerName'],
'beers' => array()
);
$brewer_pk = $row['brewerId'];
$beer_qry = $func->getBeers($brewer_pk);
while ($beer_fet = mysqli_fetch_array($beer_qry))
{
$tmp = array(
'beerid' => $beer_fet['beerid'],
'productName' => $beer_fet['productName'],
'ibu' => $beer_fet['ibu'],
'abc' => $beer_fet['abv'],
'notes' => $beer_fet['notes'],
'style' => $beer_fet['style'],
'sizes' => array()
);
$beer_pk = $tmp['beerid'];
$size_qry = $func->getSizes($beer_pk);
while ($size_fet = mysqli_fetch_array($size_qry))
{
$tmp['sizes'][] = array(
'beerId' => $size_fet['beerId'],
'size' => $size_fet['size'],
);
}
$row_array['beers'][] => $tmp;
}
array_push($json_response, $row_array);
}
echo json_encode($json_response);
In order to simplify the referencing somewhat, I've rewritten the beers to be created in a $tmp variable, which now also has a 'sizes' array to which the various sizes will be appended.
After the beers and sizes are added, the $tmp will be added to the beers.
Do note that you will now be performing some more database queries, as it now (as requested) fetches the sizes per beer and not just for the last one.