I want to the key or reference_id detail (as both are same value) when the art_ean value contains 400004471.
{
"TD0000000000993": {
"reference_id": "TD0000000000993",
"art_ean": "400004481|,400004491|,400004471|"
},
"TD0000000000992": {
"reference_id": "TD0000000000992",
"art_ean": "400004482|,400004492|,400004472|"
}
}
Your json is not valid. You should remove the last , on each object. You can use a list to have some more details https://jsonlint.com.
Here is what I believe that you want.
<?php
$data = '{
"TD0000000000993": {
"reference_id": "TD0000000000993",
"art_ean": "400004481|,400004491|,400004471|"
},
"TD0000000000992": {
"reference_id": "TD0000000000992",
"art_ean": "400004482|,400004492|,400004472|"
}
}';
$decodedData = \json_decode($data, true);
$result = array_column(
array_filter($decodedData, function($data) {
return false !== strpos($data['art_ean'], '400004471');
}),
'reference_id'
);
Related
I am trying to create a do-while loop, which checks if a value is still present in a JSON - my basic idea is of repeatedly calling an API while it does have a particular value - at the end when the JSON doesn't have the value, the loop will finish running.
Is this possible? How should I check if a value is present in the JSON response?
Here's what my response looks like - (btw I will be looking for the value 'offset' every-time)
{
"records": [
{
"id": "recYxbvL2ScZXt8Pf",
"fields": {
"Display": "1) ADWANI AVINASH NIRANJANKUMAR (A2019) (CP) (NN) || recYxbvL2ScZXt8Pf"
},
"createdTime": "2021-09-25T13:11:43.000Z"
},
{
"id": "reccXiBSeyMqLAVN0",
"fields": {
"Display": "2) AGARWAL NEEDHI SUNIL (A2015) (CP) (NN) || reccXiBSeyMqLAVN0"
},
"createdTime": "2021-09-25T13:11:43.000Z"
},
{
"id": "rec7G80Xihuc7cLwu",
"fields": {
"Display": "3) AGARWAL UMESH LUXMANLAL (F1990) (CP) (NN) || rec7G80Xihuc7cLwu"
},
"createdTime": "2021-09-25T13:11:43.000Z"
}
.
.
.
],
"offset": "itrwUFrVOdUJauKgs/recOA1j1y2VaRbTcs" //this value
}
Here's an example of how to do this:
<?php
const DUMMY_JSON_RESPONSES = [
'{"id":"response 1","offset":"itrwUFrVOdUJauKgs/recOA1j1y2VaRbTcs"}',
'{"id":"response 2","offset":"itrwUFrVOdUJauKgs/recOA1j1y2VaRbTcs"}',
'{"id":"response 3","offset":"itrwUFrVOdUJauKgs/recOA1j1y2VaRbTcs"}',
'{"id":"response 4"}'
];
function dummyApiRequest() {
static $i = 0;
if( $i >= count( DUMMY_JSON_RESPONSES ) ) {
$i = 0;
}
return DUMMY_JSON_RESPONSES[ $i++ ];
}
// this is the relevant code part:
do {
// do API request
$jsonResponse = dummyApiRequest();
// decode JSON response into an associative array
$response = json_decode( $jsonResponse, true );
// json_decode() will return null on error
if( $response !== null ) {
// output dummy id key for demonstration purposes
var_dump( $response[ 'id' ] );
}
}
while( $response !== null && isset( $response[ 'offset' ] ) );
This is my array
array(
['studentId'=>"M100030","isbn"=>"0199535566",'price'=>"15.00"],
['studentId'=>"M100030","isbn"=>"0199535566",'price'=>"13.50"],
['studentId'=>"M100030","isbn"=>"0143105426",'price'=>"20.00"],
['studentId'=>"M100035","isbn"=>"1604501480",'price'=>"21.00"],
['studentId'=>"M100035","isbn"=>"1604501480",'price'=>"23.00"],
['studentId'=>"M100035","isbn"=>"0199535566",'price'=>"14.00"],
['studentId'=>"M103233","isbn"=>"0061964360",'price'=>"18.50"],
);
I want to group the studentId and isbn then sum up the price to JSON
{
"M100030":{
"0199535566":{
"amount":"28.50"
},
"0143105426":{
"amount":"20.00"
}
},
"M100035":{
"1604501480":{
"amount":"44.00"
},
"0199535566":{
"amount":"14.00"
}
},
"M103233":{
"0061964360":{
"amount":"18.50"
}
}
}
The method I tried so far to group the studentId and isbn, but not able to get the expected result. Anyone can correct my code?
foreach ($check['rentout'] as $key=> $values)
{
$keys = $values['studentId'];
if (!array_key_exists($keys,$trx)){
$trx[$keys] = array('isbn'=>$values['isbn'],'amount'=>$values['price']);
}else{
$trx[$keys]['amount'] = $trx[$keys]['amount']+$values['price'];
}
}
$students = array(
['studentId'=>"M100030","isbn"=>"0199535566",'price'=>"15.00"],
['studentId'=>"M100030","isbn"=>"0199535566",'price'=>"13.50"],
['studentId'=>"M100030","isbn"=>"0143105426",'price'=>"20.00"],
['studentId'=>"M100035","isbn"=>"1604501480",'price'=>"21.00"],
['studentId'=>"M100035","isbn"=>"1604501480",'price'=>"23.00"],
['studentId'=>"M100035","isbn"=>"0199535566",'price'=>"14.00"],
['studentId'=>"M103233","isbn"=>"0061964360",'price'=>"18.50"],
);
I Created variable $res and I looped over $students and get the $student_id and do a test if there is no isbn for this student, If So set their amount to the initial value, and loop again if we find it again accumulate its prices to amount, and do this again and again to all students in the array.
$res = [];
foreach ($students as $key => $student) {
$student_id = $student['studentId'];
if (!isset($res[$student_id][$student["isbn"]])){
$res[$student_id][$student["isbn"]]["amount"] = $student['price'];
}else{
$res[$student_id][$student["isbn"]]["amount"] += $student['price'];
}
}
echo "<pre>";
echo json_encode($res, JSON_PRETTY_PRINT);
Print(as excpected)
{
"M100030": {
"0199535566": {
"amount": 28.5
},
"0143105426": {
"amount": "20.00"
}
},
"M100035": {
"1604501480": {
"amount": 44
},
"0199535566": {
"amount": "14.00"
}
},
"M103233": {
"0061964360": {
"amount": "18.50"
}
}
}
This is the return result of my two variables:
$resultPayment = [
[72875500, 8187000],
[14343],
[44419200,
["12332000"],
[28700250]
]
$resultId = [
["461", "462"],
[6462],
[8771],
[8461],
[5461]
]
This is the code for get the data:
for ($iii=0; $iii<count($dataInvoice); $iii++) {
$resultId[] = unserialize($dataInvoice[$iii]->invoiceid);
$resultPayment[] = unserialize($dataInvoice[$iii]->jumlahbayarid);
}
These two pieces of data are the same length and array structure, and I want to combine $id and $payment and create an object. Here are the results I expect :
[
{ "461": 72875500 },
{ "462": 8187000 },
{ 6462: 14343 },
{ 8771: 44419200 },
{ 8461: "12332000" },
{ 5461: 28700250 }
]
One possible approach is the following example:
<?php
$payment = [
[72875500, 8187000],
[14343],
[44419200],
["12332000"],
[28700250]
];
$id = [
["461", "462"],
[6462],
[8771],
[8461],
[5461]
];
$payment = call_user_func_array('array_merge', $payment);
$id = call_user_func_array('array_merge', $id);
$result = json_encode(array(array_combine($id, $payment)));
echo $result;
?>
Result:
[{"461":72875500,"462":8187000,"6462":14343,"8771":44419200,"8461":"12332000","5461":28700250}]
I have a json file stored on server & it looks like below:
{
"support_link":"#",
"support_link_2":"#",
"packs":[
{
"identifier":1,
"viewCount":0,
"downloadCount":0
},
{
"identifier":2,
"viewCount":0,
"downloadCount":0
}
]
}
By using PHP, I want to update the viewCount & downloadCount of some of the arrays inside packs.
But the thing is the data is received via a POST method to the server which contains another json with info. of which identifier to update & what param to update, & I am not able to update the existing file & save it back.
Received Json format:
{
"impressions": [
{
"identifier": "1",
"impressionCount": 2
},
{
"identifier": "100",
"impressionCount": 2
},
{
"identifier": "1000",
"impressionCount": 2000
}
],
"downloads": [
{
"identifier": "1",
"downloadCount": 10
}
]
}
What I've tried to do so far:
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig =
$json = file_get_contents('php://input');
if ($json != '') {
$properJsonFormatted = json_decode($json, true);
$impressions = $properJsonFormatted['impressions'];
$downloads = $properJsonFormatted['downloads'];
$testConfig = json_decode(file_get_contents("test_config.json"),true);
$packs = $testConfig['packs'];
foreach ($packs as &$pack) {
$packIdentifier = $pack['identifier'];
foreach ($impressions as $impression) {
$impressionIdentifier = $impression['identifier'];
if ($packIdentifier == $impressionIdentifier) {
$pack['viewCount'] += $impression['impressionCount'];
$newCount = $pack['viewCount'];
print("Id: $packIdentifier, ViewCount: $newCount\n");
}
}
}
put_file_contents("test_config.json" , $testConfig);
// print_r($testConfig);
// Save back the updated test_config.json
}
}
UPDATE
Seem to have misinterpreted the question. The actual problem seems to be much simpler.
Change this:
put_file_contents("test_config.json" , $testConfig);
To this:
file_put_contents('test_config.json', json_encode($testConfig));
Also change this:
$packs = $testConfig['packs'];
To this:
$packs = &$testConfig['packs'];
As it seems you forgot to assign that by reference, while you correctly did that in the foreach.
My OUTPUT IS
{
"session": true,
"status": true,
"msg": "user data find successfully",
"user_detail": [
{
"user_name": "asad ali",
"user_profile_pic": "localhost/uploads/image/9152108abc",
"follow": false
},
{
"image_path": [
"localhost/uploads/image/1787860Discover All In One.png",
"localhost/uploads/image/7947861Discover All In One.png"
]
},
{
"user_name": "asim kabeer",
"user_profile_pic": "localhost/uploads/image/1952108xyz",
"follow": false,
"image_path": [
"localhost/uploads/image/6547860Discover All In One.png",
"localhost/uploads/image/2152108Mart Zone - All in one.png"
]
},
My Code is
while ($rowb = $resultb->fetch_assoc())
{
$userid = $rowb['user_id'];
$user_name = $rowb['fast_name']." ".$rowb['last_name'];
$user_pic_path=$rowb['user_pic_path'];
$user_follow=$rowb['follower_id'];
$image_path=$rowb['image_path'];
if($user_follow == $user_id)
{
$user_followi = TRUE;
}
elseif($user_follow !== $user_id)
{
$user_followi = FALSE;
}
if(!isset($result[$userid]))
{
$result[] = array('user_name'=>$user_name,'user_profile_pic'=>$user_pic_path,'follow'=>$user_followi);
}
$result[$userid]['image_path'][] = $image_path;
}
$response['session']=TRUE;
$response['status']=TRUE;
$response['msg']="user data find successfully";
$response['user_detail']=$result;
echo json_encode($response);
Issue is
i want to remove gap between follow & image path in first user asad ali
if you see all image path with no gap but 1st user asad ali have 2 line gap between follow & image_path see my output
When you use $result[] = x; php add x to end of numeric index.
If you want initiate $result for user you must use:
if(!isset($result[$userid]))
{
$result[$userid] = array('user_name'=>$user_name,'user_profile_pic'=>$user_pic_path,'follow'=>$user_followi, 'image_path'=>[]);
}
$result[$userid]['image_path'][] = $image_path;
You are using $user_id in your code which will definitely have any value. You are using that as a key in
$result[$userid]['image_path'][] = $image_path;
So you have to remove $user_id so avoid index.
You can use :
if(!isset($result[$userid]))
{
$data = array('user_name'=>$user_name,'user_profile_pic'=>$user_pic_path,'follow'=>$user_followi);
$result[] = $data;
$image_path = array("localhost/uploads/image/1787860Discover All In One.png","localhost/uploads/image/7947861Discover All In One.png");
}
$result[]['image_path'] = $image_path;
$result = json_encode($result);