SimpleXMLElement from curl response - problem with #attributes - php

XML code from response:
<hints label="luggage">20</hints>
<hints label="handluggage">5</hints>
<hints label="landing"></hints>
After this function with response:
$arrayResponse = json_decode(json_encode((array)simplexml_load_string($response)), true);
I have this:
"hints" => [
0 => "20",
1 => "5",
2 => [
#attributes = [
label => "landing"
]
]
]
Keys "luggage" and "handluggage" does not exists.
How to get the KEYS with values from XML?
Example:
[
"luggage" => 20,
"handluggage" => 5,
"landing" => null
]

Solution without using json:
$response = '<root><hints label="luggage">20</hints><hints label="handluggage">5</hints><hints label="landing"></hints></root>';
$a = [];
foreach (simplexml_load_string($response)->hints as $hint) {
$value = (string)$hint;
$a[(string)$hint['label']] = $value ?: null;
}
print_r($a);

Related

PHP array diff: merge arrays recursively and show 'new' vs 'old' values in result

I would like to merge two arrays to compare old vs new values. For example, $arr1 is old values $arr2 is new values.
In case when the data is deleted $arr2 is an empty array. Example:
$arr1 = [
"databases" => [
0 => [
"id" => 1
"name" => "DB1"
"slug" => "db1"
"url" => "https://www.db1.org"
]
]
];
$arr2 = [];
For this my expected output after merge is
$merged = [
"databases" => [
0 => [
"id" => [
'old' => 1,
'new' => null
],
"name" => [
'old' => "DB1",
'new' => null
],
"slug" => [
'old' => "db1",
'new' => null
],
"url" => [
'old' => "https://www.db1.org",
'new' => null
],
]
]
];
if arr2 is different then the values should be present in the new field instead of null.
For example:
$arr1 = [
"databases" => [
0 => [
"id" => 1
"name" => "DB1"
"slug" => "db1"
"url" => "https://www.db1.org"
]
]
];
$arr2 = [
"databases" => [
0 => [
"id" => 5
"name" => "DB2"
"slug" => "db2"
"url" => "https://www.db2.com"
]
]
];
expected output:
$merged = [
"databases" => [
0 => [
"id" => [
'old' => 1,
'new' => 5
],
"name" => [
'old' => "DB1",
'new' => "DB2"
],
"slug" => [
'old' => "db1",
'new' => "db2"
],
"url" => [
'old' => "https://www.db1.org",
'new' => "https://www.db2.com"
],
]
]
];
Case 3 is when $arr1 is empty but $arr2 is populated:
$arr1 = [];
$arr2 = [
"databases" => [
0 => [
"id" => 1
"name" => "DB1"
"slug" => "db1"
"url" => "https://www.db1.org"
]
]
];
and the expected output is:
$merged = [
"databases" => [
0 => [
"id" => [
'old' => null,
'new' => 1
],
"name" => [
'old' => null,
'new' => "DB1"
],
"slug" => [
'old' => null,
'new' => "db1"
],
"url" => [
'old' => null,
'new' => "https://www.db1.org"
],
]
]
];
The inbuilt php functions cannot format the data in old vs new format so was wondering how to go about this? Any solutions/suggestions would be appreciated.
Update
Here is what I had tried before:
I had tried simple array_merge_recursive but it does not store the source array. So if you have $arr1 key not there, the final merged array will only have one value.
I tried some more recursive functions late in the night but failed so in essence didn't have anything to show for what I had tried. However, this morning, I came up with the solution and have posted it as an answer in case anyone needs to use it.
Interesting question, as long as a (non-empty) array on one side means to traverse into it and any skalar or null is a terminating node (while if any of old or new being an array would enforce traversing deeper so dropping the other non-array value):
It works by mapping both old and new on one array recursively and when the decision is to make to traverse to offer null values in case a keyed member is not available while iterating over the super set of the keys of both while null would represent no keys:
$keys = array_unique(array_merge(array_keys($old ?? []), array_keys($new ?? [])));
$merged = [];
foreach ($keys as $key) {
$merged['old'] = $old[$key] ?? null;
$merged['new'] = $new[$key] ?? null;
}
This then can be applied recursively, for which I found it is easier to handle both $old and $new as ['old' => $old, 'new' => $new] for that as then the same structure can be recursively merged:
function old_and_new(array $old = null, array $new = null): array
{
$pair = get_defined_vars();
$map =
static fn(callable $map, array $arrays): array => in_array(true, array_map('is_array', $arrays), true)
&& ($parameter = array_combine($k = array_keys($arrays), $k))
&& ($keys = array_keys(array_flip(array_merge(...array_values(array_map('array_keys', array_filter($arrays, 'is_array'))))))
)
? array_map(
static fn($key) => $map($map, array_map(static fn($p) => $arrays[$p][$key] ?? null, $parameter)),
array_combine($keys, $keys)
)
: $arrays;
return $map($map, $pair);
}
print_r(old_and_new(new: $arr2));
Online demo: https://3v4l.org/4KdLs#v8.0.9
The inner technically works with more than two arrays, e.g. three. And it "moves" the array keys upwards, similar to a transpose operation. Which btw. there is a similar question (but only similar, for the interesting part in context of your question it is not answered and my answer here doesn't apply there directly):
Transposing multidimensional arrays in PHP
After reviewing my own code here is the solution I came up with. I am posting it here in case someone else needs a solution for this:
/**
* Function to merge old and new values to create one array with all entries
*
* #param array $old
* #param array $new
* #return void
*/
function recursiveMergeOldNew($old, $new) {
$merged = array();
$array_keys = array_keys($old) + array_keys($new);
if($array_keys) {
foreach($array_keys as $key) {
$oldChildArray = [];
$newChildArray = [];
if(isset($old[$key])) {
if(!is_array($old[$key])) {
$merged[$key]['old'] = $old[$key];
} else {
$oldChildArray = $old[$key];
}
} else {
$merged[$key]['old'] = null;
}
if(isset($new[$key])) {
if( !is_array($new[$key])) {
$merged[$key]['new'] = $new[$key];
} else {
$newChildArray = $new[$key];
}
} else {
$merged[$key]['new'] = null;
}
if($oldChildArray || $newChildArray) {
$merged[$key] = recursiveMergeOldNew($oldChildArray, $newChildArray);
}
}
}
return $merged;
}
Note - this solution needs testing.

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

Transform data with Laravel helpers

I have an array with the following format:
[
{
"stat_month": "01-2019",
"in_sum": 45443,
"out_sum": 42838,
"balance": 2605
},
{...}
]
But I want to transform this array, hopefully in one operation, to this:
[
"labels" => ["01-2019", "02-2019", "03-2019"],
"in_sum" => [45443, 60947, 56734],
"out_sum" => [42838, 42151, 75486],
"balance" => [2605, 18796, -18752]
]
Any ideas how to solve this in one operation with collection helper functions?
Look at mapToGroups in Laravel Collections:
https://laravel.com/docs/5.8/collections#method-maptogroups
or this solution:
$obj1 = new \stdClass;
$obj1->stat_month = "01-2019";
$obj1->in_sum = 45443;
$obj1->out_sum = 42838;
$obj1->balance = 2605;
$obj2 = new \stdClass;
$obj2->stat_month = "02-2019";
$obj2->in_sum = 55443;
$obj2->out_sum = 52838;
$obj2->balance = 3605;
$collection = collect([
$obj1,$obj2
]);
$aResult = [
'labels' => [],
'in_sum' => [],
'out_sum' => [],
'balance' => []
];
$collection->each(function ($item, $key) use (&$aResult) {
$aResult['labels'][] = $item->stat_month;
$aResult['in_sum'][] = $item->in_sum;
$aResult['out_sum'][] = $item->out_sum;
$aResult['balance'][] = $item->balance;
});
Result:
array:4 [▼
"labels" => array:2 [▼
0 => "01-2019"
1 => "02-2019"
]
"in_sum" => array:2 [▼
0 => 45443
1 => 55443
]
"out_sum" => array:2 [▼
0 => 42838
1 => 52838
]
"balance" => array:2 [▼
0 => 2605
1 => 3605
]
]
You can do this is php like this:
<?php
$array = '[
{
"stat_month": "01-2019",
"in_sum": 45443,
"out_sum": 42838,
"balance": 2605
},
{
"stat_month": "01-2019",
"in_sum": 45443,
"out_sum": 42838,
"balance": 2605
},
{
"stat_month": "01-2019",
"in_sum": 45443,
"out_sum": 42838,
"balance": 2605
}
]';
$array = json_decode($array, true);
$arrayResult = [
'stat_month' => array_column($array, 'stat_month'),
'in_sum' => array_column($array, 'in_sum'),
'out_sum' => array_column($array, 'out_sum'),
'balance' => array_column($array, 'balance')
];
echo "<pre>";
print_r($arrayResult);
?>
You can use simplified array_map() and receive desired output:
$i = 0;
$tmp = ['labels'=>[],'in_sum'=>[],'out_sum'=>[],'balance'=>[]];
array_map(function($obj) use (&$tmp, $i){
foreach($tmp as &$val){
$val[] = array_values(((array)$obj))[$i];
$i++;
}
},$ar);
Demo
Or just simple foreach loop:
$tmp = ['labels'=>[],'in_sum'=>[],'out_sum'=>[],'balance'=>[]];
foreach($ar as $obj) {
$i = 0;
foreach($tmp as &$val){
$val[] = array_values(((array)$obj))[$i];
$i++;
}
}
Demo2
You can replace and re-write this code with Laravel map() function. Try to use dynamic loops instead of predefined object's properties.

PHP wrap array elements in separate arrays

I have the following array:
$arr = [
"elem-1" => [ "title" => "1", "desc" = > "" ],
"elem-2" => [ "title" => "2", "desc" = > "" ],
"elem-3" => [ "title" => "3", "desc" = > "" ],
"elem-4" => [ "title" => "4", "desc" = > "" ],
]
First I need to change the value from [ "title" => "1", "desc" = > "" ] to 1 (title's value).
I did this using array_walk:
array_walk($arr, function(&$value, $key) {
$value = $value["title"];
});
This will replace my value correctly. Our current array now is:
$arr = [
"elem-1" => "1",
"elem-2" => "2",
"elem-3" => "3",
"elem-4" => "4",
]
Now, I need to transform each element of this array into its own subarray. I have no idea on how to do this without a for loop. This is the desired result:
$arr = [
[ "elem-1" => "1" ],
[ "elem-2" => "2" ],
[ "elem-3" => "3" ],
[ "elem-4" => "4" ],
]
You can change your array_walk callback to produce that array.
array_walk($arr, function(&$value, $key) {
$value = [$key => $value["title"]];
});
Run the transformed array through array_values if you need to get rid of the string keys.
$arr = array_values($arr);
To offer an alternative solution you could achieve all of this with array_map
<?php
$arr = [
"elem-1" => [ "title" => "1", "desc" => "" ],
"elem-2" => [ "title" => "2", "desc" => "" ],
"elem-3" => [ "title" => "3", "desc" => "" ],
"elem-4" => [ "title" => "4", "desc" => "" ],
];
function convertToArray($key,$elem){
return [$key => $elem['title']];
}
$arr = array_map("convertToArray", array_keys($arr), $arr);
echo '<pre>';
print_r($arr);
echo '</pre>';
?>
outputs
Array
(
[0] => Array
(
[elem-1] => 1
)
[1] => Array
(
[elem-2] => 2
)
[2] => Array
(
[elem-3] => 3
)
[3] => Array
(
[elem-4] => 4
)
)
It doesn't make much sense to use array_walk() and modify by reference because the final result needs to have completely new keys on both levels. In other words, the output structure is completely different from the input and there are no salvageable/mutable parts. Mopping up the modified array with array_values() only adds to the time complexity cost.
array_map() has to bear a cost to time complexity too because array_keys() must be passed in as an additional parameter.
If you want to use array_walk(), use use() to modify the result array. This will allow you to enjoy the lowest possible time complexity.
More concise than array_walk() and cleaner to read, I would probably use a classic foreach() in my own project.
Codes: (Demo)
$result = [];
array_walk(
$arr,
function($row, $key) use(&$result) {
$result[] = [$key => $row['title']];
}
);
Or:
$result = [];
foreach ($arr as $key => $row) {
$result[] = [$key => $row['title']];
}
var_export($result);
You need to use array_map like
$new_arr= array_map(function($key,$val){
return [$key => $val['title']];},array_keys($arr),$arr);

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