I m using file upload with react and axios and fileupload working fine. and currently i am using fixed id in data.append('customeId', '123456'); but i want to use id value dynamic bcz there are multiple user. i want to use this id like let customeId = localStorage.getItem("customeId");. please help me use id value dynamic.
i am currently using
uploadFile = ({ target: { files } }) =>{
console.log( files[0] )
let data = new FormData();
data.append('customeId', '123456');
data.append( 'file', files[0] )
// data.append = localStorage.getItem("brokerId");
const options = {
onUploadProgress: (progressEvent) => {
const {loaded, total} = progressEvent;
let percent = Math.floor( (loaded * 100) / total )
console.log( `${loaded}kb of ${total}kb | ${percent}%` );
if( percent < 100 ){
this.setState({ uploadPercentage: percent })
}
}
}
axios.post("https://apimarkp.com/user/", data, options).then(res => { }
What i want
uploadFile = ({ target: { files } }) =>{
let customeId = localStorage.getItem("customeId");
console.log( files[0] )
let data = new FormData();
data.append('customeId', 'customeId');
data.append( 'file', files[0] )
// data.append = localStorage.getItem("brokerId");
const options = {
onUploadProgress: (progressEvent) => {
const {loaded, total} = progressEvent;
let percent = Math.floor( (loaded * 100) / total )
console.log( `${loaded}kb of ${total}kb | ${percent}%` );
if( percent < 100 ){
this.setState({ uploadPercentage: percent })
}
}
}
axios.post("https://apimarkp.com/user/", data, options).then(res => { }
when you log in at the APP you should write on the localStorage
localStorage.setItem("customeId", customer.Id);
now you can use in your function:
uploadFile = ({ target: { files } }) =>{
let customeId = localStorage.getItem("customeId");
Related
I am communicating through web view. My question is to send the pictures from the mobile phone to the web view.
I call API here. I don't know how to send it to the web view. I know how to send only the Key,Value,which consists of a string.
The code I'm taking pictures of phone.
let imagePicker: UIImagePickerController! = UIImagePickerController()
let imagePicker: UIImagePickerController! = UIImagePickerController()
var captureImage: UIImage!
var flagImageSave = false
#IBAction func btnLoadImageFromLibray(_ sender: UIButton) {
if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)) {
flagImageSave = false
imagePicker.delegate = self
imagePicker.sourceType = .photoLibrary
imagePicker.mediaTypes = [kUTTypeImage as String]
imagePicker.allowsEditing = true
present(imagePicker, animated: true, completion: nil)
}else{
myAlert("photo album inaccessable", message: "application cannot access the photo album")
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let mediaType = info[UIImagePickerControllerMediaType] as! NSString
if mediaType.isEqual(to: kUTTypeImage as NSString as String){
captureImage = info[UIImagePickerControllerOriginalImage] as! UIImage
if flagImageSave {
UIImageWriteToSavedPhotosAlbum(captureImage, self, nil, nil)
}
imgView.image = captureImage
}else if mediaType.isEqual(to: kUTTypeMovie as NSString as String){
if flagImageSave {
videoURL = (info[UIImagePickerControllerMediaURL] as! URL)
UISaveVideoAtPathToSavedPhotosAlbum(videoURL.relativePath, self, nil, nil)
}
}
self.dismiss(animated: true, completion: nil)
}
API code being received by server on Sping Project
#RequestMapping(value="/sendimage", method = RequestMethod.POST)
public #ResponseBody Map<String, Object> pr_image(HttpServletRequest webRequest
, #RequestParam(value="image", required=false) MultipartFile image
) {
Map<String, Object> param = new HashMap<String, Object>();
Map<String, Object> result = new HashMap<String, Object>();
Map<String, Object> validationMap = ValidationUtils.ValidationOfKeys(webRequest);
if (!validationMap.get("res").equals("sucess")) return validationMap;
String num = (webRequest.getParameter("num") != null) ? webRequest.getParameter("num") : "";
String imagePath = "";
if (image != null) {
String Extension = Config.USER_PROFILE_IMAGE_EXT;
String fileName = "_" + Utils.getCurrentTime("yyyyMMddHHmmssSSS");
imagePath = Define.CONTENTS_FILE_PATH_4 + fileName + Extension ;
File saveDir = new File(Define.CONTENTS_SAVE_PATH + Define.CONTENTS_FILE_PATH_4);
if (!saveDir.isFile()) saveDir.mkdirs();
image.transferTo(new File(Define.CONTENTS_SAVE_PATH + imagePath));
String fileName_thumbnail = fileName + "_thumb" + Extension;
File thumbnail = new File(Define.CONTENTS_SAVE_PATH + Define.CONTENTS_FILE_PATH_4 + fileName_thumbnail);
thumbnail.getParentFile().mkdirs();
Thumbnails.of(saveDir + "/" + fileName + Extension).size(Config.USER_PROFILE_IMAGE_WIDTH, Config.USER_PROFILE_IMAGE_HEIGHT).outputFormat("jpg").toFile(thumbnail);
}
...
How can I transfer pictures with my data to spring server?
I have to send not just images, but also numbers in strings. Look at my server code.
Thanks you in advance
You can solve this problem by using the Alamofire module.
You can add 'Alamofire', '~> 4.8.2' in podfile
pod install
I'm use Alamofire version 4.8.2
Usage
func ImageUpload(_ image: UIImage) {
guard image.jpegData(compressionQuality: 0.9) != nil else {
self.dismiss(animated: true, completion: nil)
return
}
let imagedata = image.jpegData(compressionQuality: 0.9)
let uploadDict = ["num": "123456789"] as [String:String]
let headers: HTTPHeaders = ["key":"val"] // Use this if you need to add api headers
Alamofire.upload(multipartFormData: { MultipartFormData in
MultipartFormData.append(imagedata!, withName: "image" , fileName: "image.jpg" , mimeType: "image/jpg")
for(key,value) in uploadDict{
MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)}
},to: "\(url)", headers: headers, encodingCompletion: {
EncodingResult in
switch EncodingResult{
case .success(let upload, _, _):
upload.responseJSON { response in
guard let json = response.result.value! as? [String: Any] else {
return
}
print(json)
}
case .failure(let encodingError):
print("ERROR RESPONSE: \(encodingError)")
}
})
}
use UIImageJPEGRepresentation to convert UIImage to NSData, and upload use
guard let data = UIImageJPEGRepresentation(image, 0.8) else {
return
}
Alamofire.upload(multipartFormData: { (form) in
form.append(data, withName: "image", mimeType: "image/jpg")
}, to: url) { (result) in
}
Is it possible to fail my request?
I would like to put Status = KO in asLongAs() section. My condition is like, if I get WorkflowFailed = True or Count > 8 then I want to fail that request using Status = KO.
I have seen somewhere about session.markAsFailed but how and where to use this?
Thanks.
Here is the code,
class LaunchResources extends Simulation {
val scenarioRepeatCount = Integer.getInteger("scenarioRepeatCount", 1).toInt
val userCount = Integer.getInteger("userCount", 1).toInt
val UUID = System.getProperty("UUID", "24d0e03")
val username = System.getProperty("username", "p1")
val password = System.getProperty("password", "P12")
val testServerUrl = System.getProperty("testServerUrl", "https://someurl.net")
val count = new java.util.concurrent.atomic.AtomicInteger(0)
val httpProtocol = http
.baseURL(testServerUrl)
.basicAuth(username, password)
.connection("""keep-alive""")
.contentTypeHeader("""application/vnd+json""")
val headers_0 = Map(
"""Cache-Control""" -> """no-cache""",
"""Origin""" -> """chrome-extension://fdmmgasdw1dojojpjoooidkmcomcm""")
val scn = scenario("LaunchAction")
.repeat (scenarioRepeatCount) {
exec(http("LaunchAResources")
.post( """/api/actions""")
.headers(headers_0)
.body(StringBody(s"""{"UUID": "$UUID", "stringVariables" : {"externalFilePath" : "/Test.mp4"}}"""))
.check(jsonPath("$.id").saveAs("WorkflowID")))
.exec(http("SaveWorkflowStatus")
.get("""/api/actions/{$WorkflowID}""")
.headers(headers_0)
.check(jsonPath("$.status").saveAs("WorkflowStatus")))
}
.asLongAs(session => session.attributes("WorkflowStatus") != "false" && count.getAndIncrement() < 8) {
doIf(session => session("WorkflowFailed").validate[String].map(WorkflowFailed => !WorkflowFailed.contains("true")).recover(true))
{
pause(pauseTime)
.exec(http("SaveWorkflowStatus")
.get("""/api/actions/${WorkflowID}""")
.headers(headers_0)
.check(jsonPath("$.running").saveAs("WorkflowStatus"))
.check(jsonPath("$.failed").saveAs("WorkflowFailed")))
.exec(session => {
val wflowStatus1 = session.get("WorkflowStatus").asOption[String]
val wflowFailed1 = session.get("WorkflowFailed").asOption[String]
println("Inner Loop Workflow Status: ========>>>>>>>> " + wflowStatus1.getOrElse("COULD NOT FIND STATUS"))
println("Inner Loop Workflow Failed?? ========>>>>>>>> " + wflowFailed1.getOrElse("COULD NOT FIND STATUS"))
println("Count =====>> " + count)
session})
}
}
setUp(scn.inject(atOnceUsers(userCount))).protocols(httpProtocol)
}
there's a method available on the session
exec(session => session.markAsFailed)
The official Solr Java API has a deleteByQuery operation where we can delete documents that satisfy a query. The AWS CloudSearch SDK doesn't seem to have matching functionality. Am I just not seeing the deleteByQuery equivalent, or is this something we'll need to roll our own?
Something like this:
SearchRequest searchRequest = new SearchRequest();
searchRequest.setQuery(queryString);
searchRequest.setReturn("id,version");
SearchResult searchResult = awsCloudSearch.search(searchRequest);
JSONArray docs = new JSONArray();
for (Hit hit : searchResult.getHits().getHit()) {
JSONObject doc = new JSONObject();
doc.put("id", hit.getId());
// is version necessary?
doc.put("version", hit.getFields().get("version").get(0));
doc.put("type", "delete");
docs.put(doc);
}
UploadDocumentsRequest uploadDocumentsRequest = new UploadDocumentsRequest();
StringInputStream documents = new StringInputStream(docs.toString());
uploadDocumentsRequest.setDocuments(documents);
UploadDocumentsResult uploadResult = awsCloudSearch.uploadDocuments(uploadDocumentsRequest);
Is this reasonable? Is there an easier way?
You're correct that CloudSearch doesn't have an equivalent to deleteByQuery. Your approach looks like the next best thing.
And no, version is not necessary -- it was removed with the CloudSearch 01-01-2013 API (aka v2).
CloudSearch doesn't provide delete as query, it supports delete in a slightly different way i.e. build json object having only document id (to be deleted) and operation should be specified as delete. These json objects can be batched together but batch size has to be less than 5 MB.
Following class supports this functionality, you just pass its delete method the array of ids to be deleted:
class AWS_CS
{
protected $client;
function connect($domain)
{
try{
$csClient = CloudSearchClient::factory(array(
'key' => 'YOUR_KEY',
'secret' => 'YOUR_SECRET',
'region' => 'us-east-1'
));
$this->client = $csClient->getDomainClient(
$domain,
array(
'credentials' => $csClient->getCredentials(),
'scheme' => 'HTTPS'
)
);
}
catch(Exception $ex){
echo "Exception: ";
echo $ex->getMessage();
}
//$this->client->addSubscriber(LogPlugin::getDebugPlugin());
}
function search($queryStr, $domain){
$this->connect($domain);
$result = $this->client->search(array(
'query' => $queryStr,
'queryParser' => 'lucene',
'size' => 100,
'return' => '_score,_all_fields'
))->toArray();
return json_encode($result['hits']);
//$hitCount = $result->getPath('hits/found');
//echo "Number of Hits: {$hitCount}\n";
}
function deleteDocs($idArray, $operation = 'delete'){
$batch = array();
foreach($idArray as $id){
//dumpArray($song);
$batch[] = array(
'type' => $operation,
'id' => $id);
}
$batch = array_filter($batch);
$jsonObj = json_encode($batch, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
print_r($this->client->uploadDocuments(array(
'documents' => $jsonObj,
'contentType' =>'application/json'
)));
return $result['status'] == 'success' ? mb_strlen($jsonObj) : 0;
}
}
Modified for C# - Deleting uploaded document in cloud search
public void DeleteUploadedDocuments(string location)
{
SearchRequest searchRequest = new SearchRequest { };
searchRequest = new SearchRequest { Query = "resourcename:'filepath'", QueryParser = QueryParser.Lucene, Size = 10000 };
searchClient = new AmazonCloudSearchDomainClient( ConfigurationManager.AppSettings["awsAccessKeyId"] , ConfigurationManager.AppSettings["awsSecretAccessKey"] , new AmazonCloudSearchDomainConfig { ServiceURL = ConfigurationManager.AppSettings["CloudSearchEndPoint"] });
SearchResponse searchResponse = searchClient.Search(searchRequest);
JArray docs = new JArray();
foreach (Hit hit in searchResponse.Hits.Hit)
{
JObject doc = new JObject();
doc.Add("id", hit.Id);
doc.Add("type", "delete");
docs.Add(doc);
}
UpdateIndexDocument<JArray>(docs, ConfigurationManager.AppSettings["CloudSearchEndPoint"]);
}
public void UpdateIndexDocument<T>(T document, string DocumentUrl)
{
AmazonCloudSearchDomainConfig config = new AmazonCloudSearchDomainConfig { ServiceURL = DocumentUrl };
AmazonCloudSearchDomainClient searchClient = new AmazonCloudSearchDomainClient( ConfigurationManager.AppSettings["awsAccessKeyId"] , ConfigurationManager.AppSettings["awsSecretAccessKey"] , config);
using (Stream stream = GenerateStreamFromString(JsonConvert.SerializeObject(document)))
{
UploadDocumentsRequest upload = new UploadDocumentsRequest()
{
ContentType = "application/json",
Documents = stream
};
searchClient.UploadDocuments(upload);
};
}
I am developing search indexing using PHP and AJAX to make it powerful.
When I scan it using burpsuit or other security scanner, SQL injection appears in AJAX code and I can't find any solution for it. The code is below:
<?php
require_once 'Connections/connect.php';
if($_GET['type'] == 'mobile'){
$result = mysql_query("SELECT mobilep FROM dictionary where mobilep LIKE '".$_GET['name_startsWith']."%'");
$data = array();
while ($row = mysql_fetch_array($result)) {
array_push($data, $row['mobilep']);
}
echo json_encode($data);
}
?>
This is very bad... you're using the deprecated mysql adapter.
http://php.net/manual/en/book.pdo.php
Use pdo and binds, here's a full prototype:
class MySql
{
private $sDbName = '';
private $sUsername = '';
private $sPassword = '';
private $sHost = '';
private $oConnection = null;
public function __construct()
{
$this->oConnection = new PDO(
'mysql:host='
. $this->sHost
. ';dbname='
. $this->sDbName,
$this->sUsername,
$this->sPassword
);
}
public function getDb()
{
return $this->oConnection;
}
}
$aReturn[ 'data' ] = '';
if( !empty( $_GET[ 'type' ] )
&& ( !empty( $_GET[ 'name_startsWith' ] )
&& ( $_GET['type'] == 'mobile' )
)
{
$oMySql = new MySql;
$oDb = $oMySql->getDb();
$sSql = "SELECT mobilep FROM dictionary where mobilep LIKE :name";
$aBinds[ ':name' ] = $_GET[ 'name_startsWith' ] . '%';
$oStmp = $oDb->prepare( $sSql );
$oMySql->bindVariables( $oStmp, $aBinds );
$oStmp->execute();
$oResults = $oStmp->fetchall();
if( !empty( $oResults ) )
{
// var_dump( $aResults );
$oErrors = $oStmp->errorInfo();
// var_dump( $oErrors );
$aReturn[ 'data' ] = $aResults;
}
}
$sJson = json_encode( $aReturn, 1 );
header( 'Content-type', 'application/json' );
echo $sJson;
(Yes, this is question over a year old. But there is no selected answer. I ran across this question in a search...)
If you are stuck with mysql_ interface functions, and can't migrate to mysqli or PDO, the best you can do is to use the mysql_real_escape_string function.
existing code:
= mysql_query(" ... LIKE '". $_GET['name_startsWith'] ."%'");
to properly escape a potentially unsafe value, before it's incorporated into the SQL text, use the mysql_real_escape_string function...
= mysql_query(" ... LIKE '". mysql_real_escape_string( $_GET['name_startsWith'] )."%'");
^^^^^^^^^^^^^^^^^^^^^^^^^ ^
I am doing a lot of operations using a below code in PHP. The issue is PHP is getting slower and slower as my data gets bigger and bigger.
My solution to fix this is to move the code in Java so it can provide a better performance as it is complied language and I can also multithread or use async functions to do multiple such operations to make it faster.
What I want to know is how to speed up this kind of operation in PHP or what other data structure should I use to improve the performance of this code. And if not PHP how can I do this in Java.
foreach ( $dataArr as $direct ) {
//total dfpimpr for the date-li combi
if ( isset( $arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']]['COUNTER_TOTALIMPR'] ) ) {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']]['COUNTER_TOTALIMPR'] += $direct[0]['DFPIMPR'];
}else {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']]['COUNTER_TOTALIMPR'] = $direct[0]['DFPIMPR'];
}
$dfpAdUnit = $direct['AD1']['DFPAD1'].'/'.$direct['AD2']['DFPAD2'];
// can go on the first level of the array as not dependent on AD1/AD2-COUNTRY
if ( isset( self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_direct'] ) ) {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ISDIRECT'] = self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_direct'];
}else {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ISDIRECT'] = 1;
}
if ( isset( self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_ron'] ) ) {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ISRON'] = self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_ron'];
}else {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ISRON'] = 0;
}
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DATE'] = $direct['DS']['DATE'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ISADEX'] = 0;
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ISMM'] = 0;
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ADVERTISER'] = $direct['DA']['ADVERTISER'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ORDID'] = $direct['DOX']['ORDID'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['ORDNAME'] = $direct['DOX']['ORDNAME'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['LINAME'] = $direct['DLI']['LINAME'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['LIID'] = $direct['DLI']['LIID'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['LISIZE'] = $direct['DSZ']['LISIZE'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['SITEID'] = $direct['PUBSITE']['SITEID'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['COUNTRYID'] = $direct['DC']['COUNTRYID'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['COUNTRY'] = $direct['DC']['COUNTRY'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPADUNIT'] = $dfpAdUnit;
//if it is passback (ISDIRECT=2) make its revenue && impr = 0
//and add its impr to a new pbImpr column
if ( isset( self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_direct'] )
&& self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_direct'] == 2 ) {
//passback imprs
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['PBIMPR'] = $direct[0]['DFPIMPR'];
//make dfpimpr for passback all 0
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPIMPR'] = $direct[0]['DFPIMPR'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPCLCKS'] = $direct[0]['DFPCLCKS'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPREV'] = 0;
//make tpimpr for passback all 0
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPIMPR'] = 0;
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPCLCKS'] = 0;
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPREV'] = 0;
}else {
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPIMPR'] = $direct[0]['DFPIMPR'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPCLCKS'] = $direct[0]['DFPCLCKS'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['DFPREV'] = $direct[0]['DFPREV'];
//include direct data into 3rd party
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPIMPR'] = $direct[0]['DFPIMPR'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPCLCKS'] = $direct[0]['DFPCLCKS'];
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPREV'] = $direct[0]['DFPREV'];
}
//include direct data into 3rd party
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TP'] = '';
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']]['TPTAGID'] = 0;
}
Follow DRY principle. That way you'll reduce the length of the code, its complexity, and - what's most important in this case - you'll get rid of several dozens of multidimensional-arrays dereferences. Also the final code will be much easier to maintain:
foreach ($dataArr as $direct) {
// create a few references to reduce "ugly" code
$counter = &$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']]['COUNTER_TOTALIMPR'];
$directStatus = &self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_direct'];
$ronStatus = &self::$orderLineitemSetting[$direct['DOX']['ORDID']][$direct['DLI']['LIID']]['setting']['is_ron'];
$dfpAdUnit = $direct['AD1']['DFPAD1'].'/'.$direct['AD2']['DFPAD2'];
if (!isset($counter)) {
$counter = 0;
}
$counter += $direct[0]['DFPIMPR'];
$e = array(
'DATE' => $direct['DS']['DATE'],
'ISADEX' => 0,
'ISMM' => 0,
'ADVERTISER' => $direct['DA']['ADVERTISER'],
'ORDID' => $direct['DOX']['ORDID'],
'ORDNAME' => $direct['DOX']['ORDNAME'],
'LINAME' => $direct['DLI']['LINAME'],
'LIID' => $direct['DLI']['LIID'],
'LISIZE' => $direct['DSZ']['LISIZE'],
'SITEID' => $direct['PUBSITE']['SITEID'],
'COUNTRYID' => $direct['DC']['COUNTRYID'],
'COUNTRY' => $direct['DC']['COUNTRY'],
'DFPADUNIT' => $dfpAdUnit,
'TP' => '',
'TPTAGID' => 0
);
$e['ISDIRECT'] = !isset($directStatus) ? 1 : $directStatus;
$e['ISRON'] = !isset($ronStatus) ? 0 : $ronStatus;
if (isset($directStatus) && $directStatus === 2) { // Hint: don't use magic numbers (2),
// create some constant with appropriate name
$e += array(
'PBIMPR' => $direct[0]['DFPIMPR'],
'DFPIMPR' => $direct[0]['DFPIMPR'],
'DFPCLCKS' => $direct[0]['DFPCLCKS'],
'DFPREV' => 0,
'TPIMPR' => 0,
'TPCLCKS' => 0,
'TPREV' => 0
);
} else {
$e += array(
'DFPIMPR' => $direct[0]['DFPIMPR'],
'DFPCLCKS' => $direct[0]['DFPCLCKS'],
'DFPREV' => $direct[0]['DFPREV'],
'TPIMPR' => $direct[0]['DFPIMPR'],
'TPCLCKS' => $direct[0]['DFPCLCKS'],
'TPREV' => $direct[0]['DFPREV']
);
}
$arrayToBeFilled[$direct['DS']['DATE']][$direct['DLI']['LIID']][$dfpAdUnit][$direct['DC']['COUNTRYID']] = $e;
}
Optimize PHP itself. Use OP code accelerator like APC (for PHP < 5.5) or even better: a JIT compiler (HHVM) as suggested by #Alasdair