How to add data to the array correctly - php

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

Related

Transpose subarray data from indexed to associative

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

php - How to insert a foreach loop inside a multidimensional array

How to insert a foreach loop inside a multidimensional array ?
I have a multidimensional array that I use to connect my website to Mailchimp. I have to check with a foreach loop the number of products that the user buys, and add these insiede a array call "lines".
This is at moment my json code, that after I will send to Mailchimp:
$json_data = '{
"id": "2'. $order->id .'",
"customer": {
"id": "71",
"email_address": "'.$order->email.'",
"opt_in_status": true,
"company": "'.$order->company_name.'",
"first_name": "'.$order->pad_firstname.'",
"last_name": "'.$order->pad_lastname.'",
"orders_count": 1,
"total_spent": 86
},
"checkout_url": "https://www.mywebsite.it/en/checkout/confirmation/",
"currency_code": "EUR",
"order_total": 86,
"lines"[{
'.$line_result.'
}]
}';
The $line_result is where I try to add the array of the products.
I know is wrong.
all the array inside the "lines" need be like this:
"lines":[
{
data product 1 ...
},
{
data product 2 ...
}
]
This is my foreach:
foreach ($order->pad_products as $product) {
$line_result['line'] = array(
"id" => "$order->id",
"product_id" => "$product->pad_product_id",
"product_title" => "$product->title",
"product_variant_id" => "$product->id",
"product_variant_title" => "$product->title",
"quantity" => "$product->pad_quantity",
"price" => "$product->prezzo",
);
};
what is the correct way to insert this data and create a multidimensional array like the one I need?
Thank you.
You just need to store all $line_result in global variable, and then, bind it to your json model :
$results = [];
foreach ($order->pad_products as $product) {
$results[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
};
$data = json_decode($json_data, true);
$data['lines'] = $results;
$json = json_encode($data);
EDIT : Script array to json
$lines = [];
foreach ($order->pad_products as $product) {
$lines[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
}
$data = [
'id' => '2'.$order->id,
'customer' => [
'id' => '71',
'email_address' => $order->email,
'opt_in_status' => true,
'company' => $order->company_name,
'first_name' => $order->pad_firstname,
'last_name' => $order->pad_lastname,
'orders_count' => 1,
'total_spent' => 86
],
'checkout_url' => 'https://www.mywebsite.it/en/checkout/confirmation',
'currency_code' => 'EUR',
'order_total' => 86,
'lines' => $lines
];
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
I want say thank you to #adrianRosi for the help and the input he gives me.
In the end I find my solution, that it's json_encode the array before add into $data in json format.
in this way:
$product_list = [];
foreach ($order->pad_products as $product) {
$product_list[] = array(
"id" => "$id",
"..." => "...",
);
};
$data_products['lines'] = $product_list;
$json_products = json_encode($data_products);
$json_products_edit = substr($json_products, 1, -1); // to delete the {}
$prezzo_totale = $order->pad_price_total;
$json_data = '{
...
...
'.$json_products_edit.'
}';

Array manipulation: Convert one array to another

For a few hours, I lost myself in an array.
I have something like this:
$results = [
"User_1" = [
"Step_1" = "accepted",
"Step_2" = "accepted",
"Step_3" = "waiting",
"Step_4" = "refused"
],
"User_2" = [
"Step_1" = "waiting",
"Step_2" = "accepted",
"Step_3" = "accepted",
"Step_4" = "refused"
],
];
I need to count (and have the sum) of all the "status" for a specific "Step".
In this case, I wish to have :
$steps = [
"Step_1" = [
'acceptedSum' => 1,
'refusedSum' => 0,
'waitingSum' => 1
],
"Step_2" =[
'acceptedSum' => 2,
'refusedSum' => 0,
'waitingSum' => 0
],
"Step_3" =[
'acceptedSum' => 1,
'refusedSum' => 0,
'waitingSum' => 1
],
"Step_4" =[
'acceptedSum' => 0,
'refusedSum' => 0,
'waitingSum' => 2
],
];
[ Nota: Number of User is not defined (1 to N) and number of Step too (1 to 4) ]
Any help will be appreciated :)
Thanks to you.
Try this, see if it works or not.
$steps = array();
$count = 0;
$keys = array_keys(current($results));
foreach($keys as $key){
$accepted = 0;
$refused = 0;
$waiting = 0;
foreach ($results as $result) {
foreach ($result as $k => $v) {
if ($key==$k&&$v == 'accepted') {
$accepted++;
}
if ($key==$k&&$v == 'refused') {
$refused++;
}
if ($key==$k&&$v == 'accepted') {
$waiting++;
}
}
}
$new_array = [
'acceptedSum' => $accepted,
'refusedSum' => $refused,
'withoutAnswerSum' => $waiting
];
$steps[$key] = $new_array;
}
print_r($steps);
You could create the existing keys dynamically. The missing keys you could add with a value of 0;
$results = [
"User_1" => [
"Step_1" => "accepted",
"Step_2" => "accepted",
"Step_3" => "waiting"
],
"User_2" => [
"Step_1" => "waiting",
"Step_2" => "accepted",
"Step_3" => "accepted"
],
"User_3" => [
"Step_1" => "refused",
"Step_2" => "refused",
"Step_3" => "waiting"
]
];
$steps = [];
$status = [];
foreach ($results as $result) {
foreach ($result as $key => $r) {
if (!array_key_exists($key, $steps)) {
$steps[$key] = [];
}
if (!array_key_exists($r."Sum", $steps[$key])) {
$steps[$key][$r."Sum"] = 0;
}
$steps[$key][$r."Sum"]++;
$status[] = $r;
}
}
foreach (array_unique($status) as $au) {
foreach ($steps as &$step) {
if (!array_key_exists($au."Sum", $step)) {
$step[$au."Sum"] = 0;
}
}
}
print_r($steps);
Php output demo
I think the output in your question is wrong, but are you looking for something like this
<?php
$results = [
"User_1" => [
"Step_1" => "accepted",
"Step_2" => "accepted",
"Step_3" => "waiting"
],
"User_2" => [
"Step_1" => "waiting",
"Step_2" => "accepted",
"Step_3" => "accepted"
],
"User_3" => [
"Step_1" => "refused",
"Step_2" => "refused",
"Step_3" => "waiting"
]
];
function sumByStatus($array, $status) {
$filtered_array = array_filter($array,function($value) use ($status) {
return $value === $status;
});
return count($filtered_array);
}
$newResult = array_map(function($item) {
return [
'acceptedSum' => sumByStatus($item, 'accepted'),
'refusedSumF' => sumByStatus($item, 'refused'),
'withoutAnswerSum' => sumByStatus($item, 'waiting')
];
}, $results);
print_r($newResult);
The output is
Array
(
[User_1] => Array
(
[acceptedSum] => 2
[refusedSum] => 0
[withoutAnswerSum] => 1
)
[User_2] => Array
(
[acceptedSum] => 2
[refusedSum] => 0
[withoutAnswerSum] => 1
)
[User_3] => Array
(
[acceptedSum] => 0
[refusedSum] => 2
[withoutAnswerSum] => 1
)
)

PHP array problems - grouping array

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

how to pass value of varibles in json

foreach ($ordersList as $object) {
$entityid = $object->entity_id; //how to give this $entityid with in json
$json='{
"orderNo":$entityid, //here i want to assign the value of $entityid
"customerCode": $customerid,
"dateOrdered": "08-07-2015",
"warehouseId" : ,
"orderLineList":
[
"productId": 1000002,
"qty": 6,
"price": 10
]
}';
}
$data = json_decode($json);
$data_string= json_encode($data);
Don't write JSON strings by hand.
$data = [
"orderNo" => $entityid, //here i want to assign the value of $entityid
"customerCode" => $customerid,
"dateOrdered" => "08-07-2015",
"warehouseId" => null ,
"orderLineList" => [
"productId": 1000002,
"qty": 6,
"price": 10,
],
];
$json = json_encode($data);
json_decode() would give an error for this:
{"orderLineList": [ "productId": 1000002 ]}
Try this code:
foreach ($ordersList as $object) {
//Start with a PHP array
//Don't mess with concatenation, you will get tangled with opening & closing quotes.
//If your information comes in a json format. Use json_decode() to convert it into a PHP array.
//$dateOrder,$warehouseId,$object->customer_id are fictious variables. Replace them with real values.
$orderArray[] = [
'orderNo' => $object->entity_id,
'customerCode' => $object->customer_id,
'dateOrdered' => $dateOrdered,
'warehouseId' => $warehouseId,
'orderLineList' => [
'productId': 1000002,
'qty': 6,
'price': 10
]
];
}
$data_string = json_encode($orderArray);

Categories