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"
}
}
Related
im having some issues adding a new item to an associative array,
This is how i'm creating my structure:
$cpdata[$count] = array(
'value' => $value->value,
'images' => array(
'color' => $value->color,
'image' => $value->image,
),
);
and this is how it looks like when i output like a json:
{
"value": "BOX",
"images": {
"color": "white",
"image": "white.png"
}
}
But i would like to add more items to images somthing like this:
{
"value": "BOX",
"images": [
{
"color": "white",
"image": "white.png"
},
{
"color": "black",
"image": "black.png"
},
{
"color": "gray",
"image": "gray.png"
}
]
}
I've tried with array_push and array_merge but i cant get it
i've tried array_push($cpdata['images'][$count]['images'], 'color'=>'red', image' => 'red.png')
Could you please help me?
Regards
Mario
In context of PHP, what you have there is a JSON variable. If that is coming to you as a string you'll have to decode it first using json_decode($string);
Then you can set up an object, populate it with the image variables and write it back to the $json object as an array, like:
<?php
// example code
$json = <<<EOT
{
"value": "BOX",
"images": {
"color": "white",
"image": "white.png"
}
}
EOT;
$json = json_decode($json);
$i = new stdClass;
$i->color = $json->images->color;
$i->image = $json->images->image;
$json->images = array($i);
After that you can push to it like
$newimage = new stdClass;
$newimage->color = "foo";
$newimage->image = "bar";
$json->images[] = $newimage;
output
print_r($json);
stdClass Object
(
[value] => BOX
[images] => Array
(
[0] => stdClass Object
(
[color] => white
[image] => white.png
)
[1] => stdClass Object
(
[color] => foo
[image] => bar
)
)
)
example https://www.tehplayground.com/oBS1SN1ze1DsVmIn
Before converting into json
$cpdata[$count] = array(
'value' => $value->value,
'images' => array(
'color' => $value->color,
'image' => $value->image,
),
);
// Cpdata array has $count which has `images` as an array and we want to push another element(array) into images array
array_push($cpdata[$count]['images'], ['color'=>'red', 'image' => 'red.png']);
This is $multidimensional data result :
[
{
"2018-11-02": [
"2"
]
},
{
"2018-11-02": [
"8",
"3"
]
}
{
"2018-11-21": [
"11",
"35",
"94",
"98",
"163"
]
},
]
$filter = [3,98,11]
How to remove object and value in $multidimensional where value not exist in $filter and after unset, the result will be turned into an object like the one below :
{
"3": 2018-11-02,
"98": 2018-11-21,
"11" : 2018-11-21
}
In my case, I am using unserialize :
for($w=0;$w<count($multidimensional);$w++) {
$hasilId2[] = (object) [
$multidimensional[$w]->date=> unserialize($multidimensional[$w]->invoiceid)
];
}
I've already try using loop :
foreach($multidimensional as $key => $value) {
if(!in_array($key, $filter)) {
unset($multidimensional[$key]);
}
}
You need a loop for the main array and a loop for the internal arrays
So it is better to put 2 loop inside each other
There is also no need to uset
You can put the correct results in a separate variable and then use it
You wanted the key to that array to be the final array value
So I used the key function to get the array key and gave the new value like this:
$result[array value] = [array key];
And finally I printed the new array:
$multidimensional = [
[
"2018-11-02" => [
"2"
]
],
[
"2018-11-02" => [
"8",
"3"
]
],
[
"2018-11-21" => [
"11",
"35",
"94",
"98",
"163"
]
],
];
$filter = [3, 98, 11];
$result = [];
foreach ($multidimensional as $val1) {
foreach (array_values($val1)[0] as $key => $val2) {
if (in_array($val2, $filter)) {
$result[$val2] = key($val1);
}
}
}
print_r($result);
Result:
Array
(
[3] => 2018-11-02
[11] => 2018-11-21
[98] => 2018-11-21
)
<?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.
I have an array:
["dyGYrcK", "tRCCMsK" ,"CM1HGi3"]
I want to convert it to json like this:
{
data: [
{
"expiry" : 0,
"tokens" : {
"0" : "dyGYrcK",
"1" : "tRCCMsK",
"2" : "CM1HGi3"
}
}
]
}
I am finding this to be very difficult. I have tried alot and I am getting this output currently:
{
"data": [
"dyGYrcK",
"tRCCMsK",
"CM1HGi3"
]
}
I am currently doing this:
return response()->json(['data' => $data], 201); //$data is array
The data array needs the keys expiry and tokens.
If you want JSON encode to set the key's you have to set them also.
So I think your array must look like:
$data = [
"expiry" => 0,
"tokens" => [
"0" => "dyGYrcK",
"1" => "tRCCMsK",
"2" => "CM1HGi3"
]
]
To get the numeric index you want inside the token structure, you need to convert your array to an object first. Then you simply add the properties to a new, "blank" object ... and finally you encode that object as JSON.
$array = ["dyGYrcK", "tRCCMsK" ,"CM1HGi3"];
$obj = new StdClass;
$obj->data[] = ['expiry' => 0, 'tokens' => (object) $array];
echo json_encode($obj);
// output:
// {"data":[{"expiry":0,"tokens":{"0":"dyGYrcK","1":"tRCCMsK","2":"CM1HGi3"}}]}
$tokens = ["dyGYrcK", "tRCCMsK" ,"CM1HGi3"] ;
$data = [
'expiry' => 0,
'tokens' => (object)$tokens
];
return response()->json(['data' => [$data]], 201);
Results in
{
"data": [
{
"expiry": 0,
"tokens": {
"0": "dyGYrcK",
"1": "tRCCMsK",
"2": "CM1HGi3"
}
}
]
}
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);