I have a JSON object that looks something like this
OBJECT $deals
[
{
"deal_id": 124563
"merchant_id": 123
"merchant_name": Merchant1
}
{
"deal_id": 456789
"merchant_id": 123
"merchant_name": Merchant1
}
{
"deal_id": 46646
"merchant_id": 456
"merchant_name": Merchant2
}
]
What I am trying to do is this right now
$category_merchants = array();
foreach ($deals as $deal) {
array_push($category_merchants, $deal->merchant_id, $deal->merchant_name)
}
$category_merchants = json_encode($category_merchants);
The new JSON object has all the merchants from the original JSON. Is there an easy way to just get the distinct merchants (merchant_name, merchant_id) in the new JSON with counts of how many times they were in the original JSON?
use array_map() like this:
array_map(function($v){return [$v->merchant_id, $v->merchant_name];}, $array);
Convert json to array
$array = json_decode($deals);
loop array to get unique merchant name
foreach($array as $key => $value) {
$category_merchants[$value['merchant_id']] = $value['merchant_name'];
$category_merchant_count[] = $value['merchant_id']; //this is to count number of merchant occurance
}
Convert category_merchants back to json
$merchant = json_encode($category_merchants);
Get number of merchant occurance
print_r(array_count_values($category_merchant_count))
One way. Just use the merchant_id as the key and increment the count:
$deals = json_decode($json, true);
foreach ($deals as $deal) {
if(!isset($category_merchants[$deal['merchant_id']])) {
$category_merchants[$deal['merchant_id']] = $deal;
$category_merchants[$deal['merchant_id']]['count'] = 1;
unset($category_merchants[$deal['merchant_id']]['deal_id']);
} else {
$category_merchants[$deal['merchant_id']]['count']++;
}
}
If you need to re-index the array then:
$category_merchants = array_values($category_merchants);
Related
I would like to get check my array of the object have title and id. I want to get all the array of objects where id exists in the existing array.
I tried using array_diff or array_intersect but error stating that it is supposed to be an array.
if (!empty(session('selected_movies'))) {
$current_movies = array_intersect($allMovies, session('selected_movies'));
}
The array of objects data
[
{
"id":"05595dd2-2f13-11ea-9e3f-42010a940008",
"title":"Harry Potter"
},
{
"id":"247d20cd-2f13-11ea-9e3f-42010a940008",
"title":"Tom and Jerry"
}
]
Existing array data
["247d20cd-2f13-11ea-9e3f-42010a940008", "51141418-4fb1-11ea-a428-7a79190f5c7d"]
You could do a simple foreach and just unset if its missing desired id
<?php
//Enter your code here, enjoy!
$array = json_decode('[
{
"id":"05595dd2-2f13-11ea-9e3f-42010a940008",
"title":"Harry Potter"
},
{
"id":"247d20cd-2f13-11ea-9e3f-42010a940008",
"title":"Tom and Jerry"
}
]');
$check = ["247d20cd-2f13-11ea-9e3f-42010a940008", "51141418-4fb1-11ea-a428-7a79190f5c7d"];
foreach($array as $index => $current){
if(!in_array($current->id,$check)) unset($array[$index]);
}
print_r($array);
alternativly if you want to create a new array
$mah = [];
foreach($array as $index => $current){
if(in_array($current->id,$check)) array_push($mah,$current);
}
print_r($mah);
I need to have data output in a very specific format to be used with something.
$product = Product::with('product_attribute_values', 'product_attribute_values.product_attribute_key')->find(2);
$product_decoded = json_decode($product, true);
I need to extract product attribute values into a specific format and it currently looks like:
I wish for it be like:
{
"Material":"Plastic",
"Printing Method":"Pad",
"Ink Colour":"Black",
"Barrel Colour":"Silver",
"Grip Colour":"Black"
}
I have attempted this:
$final_array = array();
foreach($product_decoded['product_attribute_values'] as $pav) {
$array = [
$pav['product_attribute_key']['name'] => $pav['name']
];
array_push($final_array, $array);
}
return json_encode($final_array);
This results in data looking like:
[
{"Material":"Plastic"},
{"Printing Method":"Pad"},
{"Ink Colour":"Black"},
{"Barrel Colour":"Silver"},
{"Grip Colour":"Black"}
]
How would this be achieved?
You can do it like this:
foreach($product_decoded['product_attribute_values'] as $pav) {
$array[$pav['product_attribute_key']['name']] = $pav['name'];
}
return json_encode($array);
For something like this you could use collections:
return collect($product_decoded['product_attribute_values'])
->pluck('name', 'product_attribute_key.name')
->toJson();
Alternatively, you could use the array helpers:
$finalArray = Arr::pluck($product_decoded['product_attribute_values'],'name', 'product_attribute_key.name' );
return json_encode($finalArray);
You need to have it in an object instead of an array.
$item = array("Material"=>"Plastic", "Printing Method"=>"Pad", "Ink Colour"=>"Black", "Barrel Colour"=>"Silver", "Grip Colour"=>"Black");
echo json_encode($item);
will result in this JSON:
[
{"Material":"Plastic"},
{"Printing Method":"Pad"},
{"Ink Colour":"Black"},
{"Barrel Colour":"Silver"},
{"Grip Colour":"Black"}
]
Which is correct JSON array syntax.
In order to get
{
"Material":"Plastic",
"Printing Method":"Pad",
"Ink Colour":"Black",
"Barrel Colour":"Silver",
"Grip Colour":"Black"
}
You would need soemthing like
$item->Material = "Plastic";
$item->PrintingMethod = "Pad";
$item->InkColour = "Black";
$item->Barrel Colour = "Silver";
$item->GripColour = "Black;
json_encode($item);
I am having trouble getting the name of a dynamic key from a JSON string.
I am using PHP
This is a sample of the JSON
{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}
I am using foreach to go trough the json key and get the values
foreach ($json as $obj) {
$search_term = $obj->_text;
$msg_id = $obj->msg_id;
}
But I am not sure how to get the value of the "dynamic_key" which changes every time, and because of that I also cannot get the values of "confidence and value" keys.
Any ideas on how to approach this?
Followed #Dimi, solution. This is what I ended up with
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "Entity: $key";
foreach ($data['entities'] as $keys){
$conf = $keys[0]['confidence'];
$answer = $keys[0]['value'];
echo "conf: $conf, answ: $answer";
}
}
Can you provide a couple more examples?
Or try this code and let us know if it breaks
<?php
$json='{
"_text": "this is a test",
"entities": {
"dynamic_key": [
{
"confidence": 0.99,
"value": "thi is the answer"
}
]
},
"msg_id": "1234532123"
}';
$data=json_decode($json,true);
foreach ($data['entities'] as $key=>$val)
{
echo "VALUE IS $key\n values are ";
var_dump($val);
}
Using the data you've shown, there doesn't seem to be an array for the starting JSON.
But with that data the following will use foreach to both fetch the key and the data and then another sub-loop to fetch the confidencevalue...
$search_term = $json->_text;
$msg_id = $json->msg_id;
foreach ( $json->entities as $key => $entities ) {
echo $key.PHP_EOL;
foreach ( $entities as $entity) {
echo $entity->confidence.PHP_EOL;
}
}
If you decode the JSON as an array and if the dynamic key is the only key under entities, then:
$array = json_decode($json, true);
$dynamic = current($array['entities']);
$confidence = $dynamic['confidence'];
$value = $dynamic['value'];
Or shorter:
$confidence = current($array['entities'])['confidence'];
You can probably use reset, current and maybe array_pop etc.
I have one or more object in foreach and I want to merge all the objects in one in $refJSON.
$refObj = (object) array();
foreach($items as $item) { //here Im looping Two items
$refObj->refId = $item->getId();
$refObj->refLastName = $item->getLastName();
$refObj->refPhone = $item->getPhone();
$orderObj->refEmail = $item->getEmail();
}
$refJSON = json_encode($orderObj);
var_dump($refJSON);
Output :
//just the last item object
string(92) "{
"refId":"2",
"refLastName":"Joe",
"refPhone":"xxxxxxx",
"refEmail":"example#domaine.com"
}"
The output expected is to merge all the items ids 1 and 2 something like this:
[
{
"refId":"1",
"refLastName":"Steve",
"refPhone":"xxxxxxx",
"refEmail":"foo#domaine.com"
},
{
"refId":"2",
"refLastName":"Joe",
"refPhone":"xxxxxxx",
"refEmail":"example#domaine.com"
}
]
You are just overwriting the same object each time. Build each object and add this to an array (using []) and encode the result...
$refOut = array();
foreach($items as $item) { //here Im looping Two items
$refOut[] = ['refId' => $item->getId(),
'refLastName' => $item->getLastName(),
'refPhone' => $item->getPhone(),
'refEmail' => $item->getEmail()];
}
$refJSON = json_encode($refOut);
I am parsing thorugh a eBay API response. I want to deliver this back to a website cleaner and easier to parse with JavaScript. I successfuly Parsed through the XML... but now turning that into JSON to resend back to the client is giving me some headaches.
NOTE: $resp is the response from eBay. It's their full length XML that is successfully parsed with the code below.
For example... $valueName could be Grade. And then I go into the next foreach loop and get the values for this. These values may be 10, 9.5, 9 etc.
Here is my PHP code.
$arrayName = array();
$arrayValue = array();
foreach($resp->aspectHistogramContainer->aspect as $name) {
$nameAspect = $name['name'];
//$arrayName["aspectName"] = $nameAspect;
foreach($name->valueHistogram as $value) {
$valueAspect = $value['valueName'];
//$arrayValue["aspectValue"] = $valueAspect;
}
//array_push($arrayName, $arrayValue);
}
echo json_encode($arrayName);
So, without me trying to create my own JSON, I am getting that I need. I echos results and it was similar to this...
NAME
----- Value
----- Value
----- Value
NAME
----- Value
NAME
etc etc
For a JSON response... Im looking for something like...
[
{
"name": "NAME",
"value": ["value", "value"]
}, {
"name": "name",
"value": ["value", "value"]
}
]
Any help and guidance would be greatly appreciated.
eBay's response is like this (there are A LOT more <aspect> and <valueHistogram>)
<getHistogramsResponse xmlns="http://www.ebay.com/marketplace/search/v1/services">
<ack>Success</ack>
<version>1.13.0</version>
<timestamp>2018-11-07T15:32:20.380Z</timestamp>
<aspectHistogramContainer>
<domainDisplayName>Baseball Cards</domainDisplayName>
<aspect name="Card Manufacturer">
<valueHistogram valueName="Ace Authentic">
<count>19</count>
</valueHistogram>
<valueHistogram valueName="American Caramel">
<count>2024</count>
</valueHistogram>
<valueHistogram valueName="APBA">
<count>10554</count>
</valueHistogram>
<valueHistogram valueName="Bazooka">
<count>8826</count>
</valueHistogram>
<valueHistogram valueName="Be A Player">
<count>17</count>
</valueHistogram>
<valueHistogram valueName="Bell Brand Dodgers">
<count>334</count>
To encode it (and assuming SimpleXML), then it's just a case of building each internal $aspect data array and then adding the values to it. I use (string) to ensure the data is not stored as a SimpleXMLElement, which can cause side effects...
$arrayName = array();
foreach($resp->aspectHistogramContainer->aspect as $name) {
$aspect = [ "name" => (string)$name['name']];
foreach($name->valueHistogram as $value) {
$aspect["value"][] = (string)$value['valueName'];
}
$arrayName[] = $aspect;
}
echo json_encode($arrayName);
with the sample XML, this gives...
[{"name":"Card Manufacturer","value":["Ace Authentic","American Caramel","APBA","Bazooka","Be A Player","Bell Brand Dodgers"]}]
Create one single array $resultArray and store values in it. By maintaining your current code structure with minimal changes, here is the updated code snippet,
$resultArray = array();
$i = 0; // Maintain Array Index value
foreach($resp->aspectHistogramContainer->aspect as $name) {
$resultArray[$i]["aspectName"] = (string)$name['name'];;
foreach($name->valueHistogram as $value) {
$resultArray[$i]["aspectValue"][] = (string)$value['valueName'];
}
$i++; // Increment array index to store next value
}
echo json_encode($resultArray);
$results = array();
// Parse the XML into a keyed array
foreach($resp->aspectHistogramContainer->aspect as $name) {
$nameAspect = (string) $name['name'];
$values = array();
foreach($name->valueHistogram as $value) {
$values[] = (string) $value['valueName'];
}
$results[$nameAspect] = $values;
}
// This keeps things simple - rewrite to the required JSON format
$outputForJSON = array();
foreach ($results as $name => $values) {
$outputForJSON[] = array(
"name" => $name,
"values" => $values
);
}
echo json_encode($outputForJSON);