How can I set array value to null if no data exist?
Following is my array from PHP and I am json encoding -
{
"title":"Impalz-Marketing",
"type":"Business Details",
"version":"1.0",
"login":[ ],
"business":{
"1":{
"details":{ },
"messages":[ ],
"offers":[ ],
"events":[ ],
"milestone":[ ],
"products":[ ],
"brand_exp":[ ],
"reviews":[ ],
"agg_reviews":{ }
},
"168":{
"details":{ },
"messages":[ ],
"products":[ ]
}
}
}
Number of rows are uneven in both business. How can I set data to null if no row exist?
$data = array(
'title' => 'Impalz-Marketing',
'type' => 'Business Details',
'version' => '1.0',
'login' => $login_array,
'business' => $business_details_array
);
I've tried this:
$business_details_array = array();
while($row = mysql_fetch_assoc($biz_list))
{
$business_details_array[$row['id']]['details'] = $row;
}
while($row = mysql_fetch_assoc($biz_milestone))
{
if(!empty($row['id'])){
$temp= explode(',', $row['path']);
if(count($temp) > 1) {
$row['path']= $temp;
}
$business_details_array[$row['business_id']]['milestone'][] = $row;
}else{
$business_details_array[]['milestone'][] = null; // since no data exist their wont be any business_id
}
}
I want something like this -
{
"title":"Impalz-Marketing",
"type":"Business Details",
"version":"1.0",
"login":[ ],
"business":{
"1":{
"details":{ },
"messages":[ ],
"offers":[ ],
"events":[ ],
"milestone":[ ],
"products":[ ],
"brand_exp":[ ],
"reviews":[ ],
"agg_reviews":{ }
},
"168":{
"details":{ },
"messages":[ ],
"offers": "null",
"events": "null",
"milestone": "null",
"products":[ ],
"brand_exp": "null",
"reviews": "null",
"agg_reviews": "null"
}
}
}
Add nulls to your initial array creation
$business_details_array = array();
while($row = mysql_fetch_assoc($biz_list))
{
$business_details_array[$row['id']]['details'] = $row;
$business_details_array[$row['id']]['milestone'] = null;
$business_details_array[$row['id']]['products'] = null;
$business_details_array[$row['id']]['messages'] = null;
}
while($row = mysql_fetch_assoc($biz_milestone))
{
if(!empty($row['id'])){
$temp= explode(',', $row['path']);
if(count($temp) > 1) {
$row['path']= $temp;
}
$business_details_array[$row['business_id']]['milestone'][] = $row;
}
}
you could set a default initial array for a 'business' and set its values to NULL.
and then merge the array from the DB into the default one.
$defaultBusinessVals = array(
"details" => NULL,
"messages" => NULL,
"offers" => NULL,
"events" => NULL,
"milestone" => NULL,
"products" => NULL,
"brand_exp" => NULL,
"reviews" => NULL,
"agg_reviews" => NULL
);
If the DB array is this:
$dbArr = array(
"details" => "no details",
"messages" => "my msg",
"offers" => 3,
);
and then merge the data from the DB
$res = $dbArr + $defaultBusinessVals;
or
$res = array_merge($defaultBusinessVals, $dbArr);
The result will be
$res = array(
"details" => "no details",
"messages" => "my msg",
"offers" => 3,
"events" => NULL,
"milestone" => NULL,
"products" => NULL,
"brand_exp" => NULL,
"reviews" => NULL,
"agg_reviews" => NULL
);
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;
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'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);
I need to "reformat" some data coming from an external API so it works with the nested list module of Sencha touch. I cannot change the data output of that external API. Here's an example of the data I get from the API:
$quest = array(
'gastronomy' => [
'restaurants' => [
'italians' => [
[
'title' => 'Al Castello',
'leaf' => true
],
[
'title' => 'Italia',
'leaf' => true
]
],
'asians' => [
[
'title' => 'Gautam',
'leaf' => true
],
[
'title' => 'Wok',
'leaf' => true
]
]
]
]
);
In order to make it work with sencha touch the data must look like this after "reformatting" it with a PHP Service:
$result = array(
'items' => [
[
'title' => 'gastronomy',
'items' => [
[
'title' => 'restaurants',
'items' => [
[
'title' => 'italians',
'items' => [
[
'title' => 'Al Castello',
'leaf' => true
],
[
'title' => 'Italia',
'leaf' => true
]
]
],
[
'title' => 'asians',
'items' => [
[
'title' => 'Gautam',
'leaf' => true
],
[
'title' => 'Wok',
'leaf' => true
]
]
]
]
]
]
]
]
);
I have tried every way I could think of but with no success. What really bugs me is that all keys must be renamed to items. (It's hard for me to access the deeper nested items because of that when I'm using a recursive function)
Haven't tested it, but it seems like a fairly simple recursive function should handle it.
For example:
function parseApi($arr) {
$result = array();
foreach ($arr as $key => $value) {
if (isset($value['leaf'])) {
$result[] = $value;
} else {
$result[] = array(
'title' => $key,
'items' => parseApi($value)
);
}
}
return $result;
}
$result = array( 'items' => $parseApi($quest);
You need a recursive function, and it needs to be able to tell the difference between associative and numerically-indexed arrays.
// from: http://stackoverflow.com/questions/173400/how-to-check-if-php-array-is-associative-or-sequential
function isAssoc($arr) { return array_keys($arr) !== range(0, count($arr) - 1); }
function itemize($foo) {
$output = [];
if( ! isAssoc($foo) ) {
foreach( $foo as $value ) {
if( is_array($value) ) {
$output[] = itemize($value);
} else {
$output[] = $value;
}
}
} else {
foreach( $foo as $key => $value ) {
if( is_array($value) ) {
$output[] = [
'title' => $key,
'items' => itemize($value)
];
} else {
$output[$key] = $value;
}
}
}
return $output;
}
echo json_encode(itemize($quest), JSON_PRETTY_PRINT);
Output:
[
{
"title": "gastronomy",
"items": [
{
"title": "restaurants",
"items": [
{
"title": "italians",
"items": [
{
"title": "Al Castello",
"leaf": true
},
{
"title": "Italia",
"leaf": true
}
]
},
{
"title": "asians",
"items": [
{
"title": "Gautam",
"leaf": true
},
{
"title": "Wok",
"leaf": true
}
]
}
]
}
]
}
]