How to remove array of object in PHP - php

<?php
$test = '{
"100": {
"name": "Sports",
"contentID": "100"
},
"200": {
"name": "Village",
"contentID": "200"
}
}';
$idWiseData = json_decode($test,true);
$test2 = '[
{
"contentID": "100",
"contentStatus": "active"
},
{
"contentID": "200",
"contentStatus": "active"
},
{
"contentID": "300",
"contentStatus": "active"
}
]';
$allTopics = json_decode($test2,true);
foreach ($allTopics as $key => &$topic) {
$contentInfo = [
'contentStatus' => $topic['contentStatus']
];
$topic['contentName'] = isset($idWiseData[$topic['contentID']]['name']) ? $idWiseData[$topic['contentID']]['name'] : null;
}
echo "<pre>";
print_r($allTopics);
?>
Above code is working fine, i am not getting my expected output. actually $allTopics having 3 objects (contentID 100 & 200 & 300).$idWiseData having object (contentID 100 & 200).
I want to take name value from $idWiseData and replace to $allTopics based on contentID.
contentID 300 don't have name so should not come this object.
Expected out put
Array
(
[0] => Array
(
[contentID] => 100
[contentStatus] => active
[contentName] => Sports
)
[1] => Array
(
[contentID] => 200
[contentStatus] => active
[contentName] => Village
)
)
I am getting output
Array
(
[0] => Array
(
[contentID] => 100
[contentStatus] => active
[contentName] => Sports
)
[1] => Array
(
[contentID] => 200
[contentStatus] => active
[contentName] => Village
)
[2] => Array
(
[contentID] => 300
[contentStatus] => active
[contentName] =>
)
)
Kindly anyone update my code please.

As far as I understand you, you need to unset() the index within the array if contentName is null. This can be achieved by using unset()
foreach ($allTopics as $key => &$topic) {
// your code here ....
if (is_null($topic['contentName'])) {
unset(allTopics[$key]);
}
}

You can remove a record from the array by using array_slice. But I would recommend you to change your code and have a 3rd array which must be your result, so then you don't need to change any of your source data.

You're not deleting the index from the array just setting contentName to null. Use unset to delete the index from the array.
Try this one:
<?php
$test = '{
"100": {
"name": "Sports",
"contentID": "100"
},
"200": {
"name": "Village",
"contentID": "200"
}
}';
$idWiseData = json_decode($test,true);
$test2 = '[
{
"contentID": "100",
"contentStatus": "active"
},
{
"contentID": "200",
"contentStatus": "active"
},
{
"contentID": "300",
"contentStatus": "active"
}
]';
$allTopics = json_decode($test2,true);
foreach ($allTopics as $key => &$topic) {
$contentInfo = [
'contentStatus' => $topic['contentStatus']
];
if(isset($idWiseData[$topic['contentID']]['name'])){
$topic['contentName'] = $idWiseData[$topic['contentID']]['name'];
} else {
unset($allTopics[$key]);
}
}
echo "<pre>";
print_r($allTopics);
?>

foreach ($allTopics as $key => &$topic) {
$contentInfo = [
'contentStatus' => $topic['contentStatus']
];
$topic['contentName'] = isset($idWiseData[$topic['contentID']]['name']) ? $idWiseData[$topic['contentID']]['name'] : null;
if (is_null($topic['contentName'])) {
unset($topic['contentName']);
}
}
USE THIS CODE THIS MIGHT SOLVE YOUR PROBLEM.

Related

Simplify & Optimize PHP Array

I am working on combining the array into a key with the count of repeated "option""code". My Request JSON is like this
[{
"productId": "DENSUS-MARK",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE"
},
{
"code": "HIGLIGT_OPTION_HANDLE1"
}
]
},
{
"productId": "DENSUS-MARK",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE"
}
]
},
{
"productId": "DENSUS-MARK-II",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE"
}
]
}]
After combing the "productID" and the count of ["options"]["code"] (For ProductId - DENSUS-MARK, the code "HIGLIGT_OPTION_HANDLE" count is 2. So I am getting a output like this.
{
"productId": "DENSUS-MARK",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE",
"count": 2
},
{
"code": "HIGLIGT_OPTION_HANDLE1",
"count": 1
}
]
},
{
"productId": "DENSUS-MARK-II",
"options": [
{
"code": "HIGLIGT_OPTION_HANDLE",
"count": 1
}
]
}
}
This is my current php code and I need to optimize & simply this below code
$datas = json_decode($arr,true);
$formattedData = [];
foreach ($datas as $f) {
foreach ($f['options'] as $option) {
$formattedData[$f['productID']]['productID'] = $f['productID'];
$formattedData[$f['productID']]['options']['code'][$option['code']][] = $option['code'];
}
}
foreach ($formattedData as &$data) {
$formattedOptions = [];
foreach ($data['options']['code'] as $key => $codes) {
$formattedOptions[] = [
'code' => $key,
'count' => count($codes)
];
}
$data = $formattedOptions;
}
print_r($formattedData);
Someone, could you please help me in this.
I don't know if this is the optimization you want. Meanwhile, less than two loops, I have not found. It's not quite the expected result, but you should be able to fix it if you need to.
With:
$input = array (
0 =>
array (
'productId' => 'DENSUS-MARK',
'options' =>
array (
0 =>
array (
'code' => 'HIGLIGT_OPTION_HANDLE',
),
1 =>
array (
'code' => 'HIGLIGT_OPTION_HANDLE1',
),
),
),
1 =>
array (
'productId' => 'DENSUS-MARK',
'options' =>
array (
0 =>
array (
'code' => 'HIGLIGT_OPTION_HANDLE',
),
),
),
2 =>
array (
'productId' => 'DENSUS-MARK-II',
'options' =>
array (
0 =>
array (
'code' => 'HIGLIGT_OPTION_HANDLE',
),
),
)
);
Then just:
$result = [];
foreach($input as $row) {
foreach($row['options'] as $value) {
$result[$row['productId']][$value['code']] ??=0;
$result[$row['productId']][$value['code']] += count($value);
}
}
var_export($result);
Results:
array (
'DENSUS-MARK' =>
array (
'HIGLIGT_OPTION_HANDLE' => 2,
'HIGLIGT_OPTION_HANDLE1' => 1,
),
'DENSUS-MARK-II' =>
array (
'HIGLIGT_OPTION_HANDLE' => 1,
),
)

Display data from two arrays having one common point

I have two arrays.
The first one is about exchange-rate and the display in my console is like this :
{
"exchange_rate": [
{
"id": "978",
"start_dateTime": "2021-08-01 07:35:02",
"target_value": "1.00000",
"currency_value_euro": "0.84097",
"currency_value_dollar_us": "1.00000",
"id_currency": "1",
"currency": "Dollar am\u00e9ricain",
"currency_symbol": "$US"
},
{
"id": "980",
"start_dateTime": "2021-08-01 07:35:02",
"target_value": "1.00000",
"currency_value_euro": "1.17454",
"currency_value_dollar_us": "0.71600",
"id_currency": "2",
"currency": "Livre sterling",
"currency_symbol": "\u00a3"
}
]
}
These data came from the database and I can display it by choosing particular dates with jQuery.
The second array contains only id_currency which in my console is like this : Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5
On my website, I want to be able to display specific exchange rate by specific currency and dates.
And here my problem appears, I can't find the way to loop on the first array, and loop again inside, on the second array and compare both like if first array has id_currency 1 and second array has id_currency 1 then display the complete line from first array.
I've tried several things but nothing works, at last i've tried this :
foreach ($res as $row){
$idBDD = $row['id_currency'];
$symbolBDD = $row['currency_symbol'];
echo $idBDD;
echo $symbolBDD;
//var_dump($row);
/*foreach ($arr as $line){
$idCheckbox = $line;
echo $idCheckbox;
}
if ($idBDD == $idCheckbox){
echo 'fine';
}
*/
}
I'll be grateful for your help
You need to access the array with $res["exchange_rate"] and loop through it then.
<?php
$res = [
"exchange_rate" => [
[
"id" => "978",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value" => "1.00000",
"currency_value_euro" => "0.84097",
"currency_value_dollar_us" => "1.00000",
"id_currency" => "1",
"currency" => "Dollar américain",
"currency_symbol" => "\$US"
],
[
"id" => "980",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value" => "1.00000",
"currency_value_euro" => "1.17454",
"currency_value_dollar_us" => "0.71600",
"id_currency" => "2",
"currency" => "Livre sterling",
"currency_symbol" => "£"
]
]
];
$output = null;
foreach ($res["exchange_rate"] as $row) {
if (!isset($output)) {
$output = $row;
}
$output = array_intersect_assoc($output, $row);
}
var_dump($output);
I think you could do it like this, of course if you're inside the loop, you won't need to put indices.
read more array_diff()
https://www.php.net/manual/pt_BR/function.array-diff.php
$array = [
"exchange_rate" => [
[
"id" => "978",
"start_dateTime" => "2021-08-01 07:35:02",
"target_value"=> "1.00000",
"currency_value_euro"=> "0.84097",
"currency_value_dollar_us"=> "1.00000",
"id_currency"=> "1",
"currency"=> "Dollar am\u00e9ricain",
"currency_symbol" => "US"
],[
"id"=> "980",
"start_dateTime"=> "2021-08-01 07=> 35=> 02",
"target_value"=> "1.00000",
"currency_value_euro"=> "1.17454",
"currency_value_dollar_us"=> "0.71600",
"id_currency"=> "2",
"currency"=> "Livre sterling",
"currency_symbol"=> "\u00a3"
]
]
];
$array1 = $array['exchange_rate'][0];
$array2 = $array['exchange_rate'][1];
$result = array_diff( $array1, $array2);
var_dump($result);

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

Create nested JSON with dynamic keys with PHP

I get some data from an API call and I try to construct a JSON to send it back to another API.
The final JSON must look like this:
{
"jobs": {
"MP_OFFER_ID_1": {
"job_id": "jobboard_reference_1",
"url": "url_1",
"status": 0
},
"MP_OFFER_ID_2": {
"job_id": "job_id_2",
"url": "url_2",
"status": 1
},
}
}
So under the jobs key, it's not an array of elements but a list of elements with unique keys.
And that's what I'm having trouble to get.
The data I want to parse is in an array structured like this:
Array(
[0] => Array(
[link] => some-url
[id] => 18790674
[ref] => 0015909-18790674
)
// ...
);
link has to be placed in the url key of the JSON.
id is the JSON key, in the examples it's MP_OFFER_ID_1 etc
ref has to be placed in job_id
I actually have this JSON at the end:
{
"jobs": [
[
{
"18790674": {
"job_id": "0015909-18790674",
"url": "test",
"status": 1
}
},
{
"18790678": {
"job_id": "0015892-18790678",
"url": "test",
"status": 1
}
}
]
]
}
As you can see, jobs is an array (actually it's an array of array ^^) and that's not what I want here...
I came up with this, but it was very difficult to understand what exactly you want from the very limited info in question:
<?php
$input = [
[
'id' => 18790674,
'link' => 'some-url',
'ref' => '0015909-18790674',
],
[
'id' => 18790678,
'link' => 'another-url',
'ref' => '0015909-18790678',
],
];
$output = new stdClass();
foreach ($input as $arr) {
$obj = new stdClass();
$key = $arr['id'];
$obj->job_id = $arr['id'];
$obj->url = $arr['link'];
$obj->status = '1'; // ?
$output->{$key} = $obj;
}
echo json_encode($output, JSON_PRETTY_PRINT);
Output:
{
"18790674": {
"job_id": 18790674,
"url": "some-url",
"status": "1"
},
"18790678": {
"job_id": 18790678,
"url": "another-url",
"status": "1"
}
}

How can I recreate this JSON array in PHP?

I have an array in JSON that I need to recreate in PHP.
{
"items": {
"category": "fruit",
"detail": [
{
"name": "apple",
"good": true
}
]
}
"moreItems": {
"category": "fruit",
"detail": [
{
"name": "banana",
"good": false
}
]
}
}
My hopes are to create this using PHP arrays, then json_encode it.
I've tried to set the array above to a string, and de_coded it, but I'm not getting anywhere.
Thanks.
in PHP
$arr = array("items" => array(
0 => array (
"category" => "fruit",
"detail" => array("name" => "apple", "good" => true )
)
),
"moreItems" => array(
0 => array (
"category" => "fruit",
"detail" => array("name" => "banana", "good" => false)
)
)
);
or for manual assignment that maybe useful if using loops:
$arr["items"]["category"] = "fruit";
$arr["items"]["detail"][0]["name"] = "apple";
$arr["items"]["detail"][0]["good"] = true;
$arr["moreItems"]["category"] = "fruit";
$arr["moreItems"]["detail"][0]["name"] = "banana";
$arr["moreItems"]["detail"][0]["good"] = false;
echo json_encode($arr);
will give you the same output..
Actual output in JSON
Cheers!
If you have a json (in PHP) as a string, and you want to convert them to a native PHP array you can easy do that:
<?php
function objectToArray( $object )
{
if( !is_object( $object ) && !is_array( $object ) )
{
return $object;
}
if( is_object( $object ) )
{
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}
$json = '{\
"items": {\
"category": "fruit",\
"detail": [\
{\
"name": "apple",\
"good": true\
}\
]\
}\
"moreItems": {\
"category": "fruit",\
"detail": [\
{\
"name": "banana",\
"good": false\
}\
]\
}\
}';
$array = objectToArray( json_decode($json) );
echo "<pre>".print_r($array, true)."</pre>";
That's it!
Thanks to Michael Berkowski, this worked for me. You can recreate the nested [] in the code below.
If you want to replicate the structure more truly, forcing PHP to use
stdClass objects instead of assoc arrays, you might cast the inner
ones to objects: 'detail' => array(0 => (object)array('name' =>
'banana', 'good' => false))
This below will do just fine for me.
$phpArray = array(
"items" => array(
"category" => "fruit",
"detail" => array(
0 => array(
"name" => "apple", "good" => true
)
)
),
"moreItems" => array(
"category" => "fruit",
"detail" => array(
0 => array(
"name" => "banana",
"good" => false
)
)
)
);

Categories