How to get common key and store value in comma separated in array

Here are the array

“articleCriteria”: [
{
“criteriaId”: 100,
“criteriaDescription”: “Fitting Position”,
“formattedValue”: “Front Axle Right”,
},
{
“criteriaId”: 100,
“criteriaDescription”: “Fitting Position”,
“formattedValue”: “Front Axle Left”,
}
]

iam running foreach loop because other data is also coming but for common key What i want is,

fitting_position = Front Axle Right,Front Axle Left

How to move a uploaded file to a specific drive folder in using Simple Upload in Php cURL?

My requirement is to upload a file to my google drive using Php cURL and then rename the upload file and move the file to a specific folder.

For this, I have done oAuth and successfully uploaded a file from my website to google drive using the below code.

$image = "../../../".$name;
    $apiURL = 'https://www.googleapis.com/upload/drive/v3/files?uploadType=media';
    $mime_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    $folder_id = "1WBkQQ6y0TPt2gmFR3PKCzSip_aAuuNEa";
    
    $ch1 = curl_init();    
    curl_setopt($ch1, CURLOPT_URL, $apiURL);
    curl_setopt($ch1, CURLOPT_BINARYTRANSFER, 1);
    curl_setopt($ch1, CURLOPT_POST, 1);
    curl_setopt($ch1, CURLOPT_POSTFIELDS, file_get_contents($image));
    curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch1, CURLOPT_HTTPHEADER, array('Content-Type: '.$mime_type, 'Authorization: Bearer ' . $access_token) );
    // execute cURL request
    $response=curl_exec($ch1);
    if($response === false){
        $output = 'ERROR: '.curl_error($ch1);
    } else{
        $output = $response;
    }
    // close first request handler
    curl_close($ch1);
    $this_response_arr = json_decode($response, true);

The file is uploaded as Untitled and I used the below code to rename it to a proper filename as per my requirement.

 if(isset($this_response_arr['id'])){
        $this_file_id = $this_response_arr['id'];
        $ch2 = curl_init();
        curl_setopt($ch2, CURLOPT_URL, 'https://www.googleapis.com/drive/v3/files/'.$this_file_id);
        curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, 'PATCH');
        $post_fields = array();
        $this_file_name = explode('.', $name);
        $post_fields['name'] = $this_file_name[0];
        curl_setopt($ch2, CURLOPT_POSTFIELDS, json_encode($post_fields));
        curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch2, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token) );
        $response2 = curl_exec($ch2);
        if($response2 === false){
            $output2 = 'ERROR: '.curl_error($ch2);
        } else{
            $output2 = $response2;
        }
       
        curl_close($ch2);
        $this_response2 = json_decode($response2, true);
        }

Now I want to move this uploaded file in the Google drive root folder to a specific folder. I tried using “Parents” , “addParents”, “removeParents” parameters but none of them is working.

        if($this_response2['id']){
        $this_f_id = $this_response2['id'];
$ch3 = curl_init();
curl_setopt($ch3, CURLOPT_URL, 'https://www.googleapis.com/drive/v3/files/'.$this_f_id);
curl_setopt($ch3, CURLOPT_CUSTOMREQUEST, 'PATCH');
curl_setopt($ch3, CURLOPT_POST, 1);
$post_fields1 = array();
$post_fields1['addParents'] = $folder_id;
$post_fields1['removeParents'] = "root";
curl_setopt($ch3, CURLOPT_POSTFIELDS, json_encode($post_fields1));
curl_setopt($ch3, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch3, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Bearer ' . $access_token) );
$response3 = curl_exec($ch3);
if($response3 === false){
    $output3 = 'ERROR: '.curl_error($ch3);
} else{
    $output3 = $response3;
}
curl_close($ch3);

}

Any help would be appreciated.

Compare values using strpos – PHP

I am trying to return the user_id if value matches with any comma separated value, I am using strpos but I don’t why is it not working with 3rd case:

To Compare: (This value is stored in $myArray variable)

Array
(
    [0] => cloud
    [1] => ai
    [2] => test
)

Compare with: (This value is stored in $array_meta_values variable)

Array
(
    [0] => Array
        (
            [tags] => cloud,ai
            [user_id] => 1
        )

    [1] => Array
        (
            [tags] => cloud,ai,test
            [user_id] => 108
        )

    [2] => Array
        (
            [tags] => storage,backup,ai
            [user_id] => 101
        )

)



function searchForId($meta_value, $array)
{

    foreach ($array as $key => $val) {
        if (strpos($val['tags'], $meta_value)) {
            return $val['user_id'];
        }
    }
}

foreach ($myArray as $usertags) {
        $userids[] = searchForId($usertags, $array_meta_values);
    }
print_r($userids);

Getting this Output:

Array
(
    [1] => 1
    [2] => 108
)

It was supposed to add 101 as third element in output array but don’t know why it is not working.

Any help appreciated.

Laravel, MariaDB timestamp column without default and onupdate trigger

I have following migration:

Schema::create('auctions', function (Blueprint $table) {
    $table->id();
    $table->timestamp('expired_at');
    $table->timestamp('sold_at')->nullable()->default(null);
    // other fields
});

Which creates a table with this structure:
enter image description here

Every time I try to update sold_at field only, It changes the expire_at field also, which is so annoying and against my project’s logic! How should I fix my migration to prevent this?

My update record code:

Auction::query()->where('id',1)->update([
    'sold_at' => now()
]);

Eloquent query, access scope function from within subquery

I have the a scope function for my user table (User.php):

public function scopeWherePaidSubscriber(Builder $query)
{
    return $query->where(....)->where(...);
}

I am trying to access this scope from a subquery looking like this:

$count = UserCalendar::whereIn('user_id', function($que) use ($cid) { 
        $que->select('id')->from('user')->where('corporation_id', $cid)->wherePaidSubscriber();
    })->distinct('user_id')->count();

But then I noticed than I couldn’t access the scope because I am not using User::wherePaidSubscriber().
Is there a way for me to access the scope without having to copy paste it?

How to authenticate for FCM Rest API using API Key?

I need to send a notification using FCM REST API. However, I am unable to authenticaate using an API key at the moment. The below is the API to hit.

https://fcm.googleapis.com/v1/projects/proj-name/messages:send?key=XXX

The error I receive is as follows:

{
    "error": {
        "code": 401,
        "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "status": "UNAUTHENTICATED"
    }
}

The backend is in PHP so there isn’t any supported package for it. Hence, I am trying to use it for sending the notification. The above API seem to take oauth 2 access token or login cookie or some auther vaidation method. However, I need to send it from my own REST API. How can I authenticate from PHP to the above API and send the notificaiton properly?

Can someone help Me with payment system with php and handling request [closed]

So i use payment method with midtrans and its works. the problem was to use handler/ request to update mysql, i need to change status database. Help me please…..

~
<?php 

namespace Midtrans;

    require('admin/inc/db_config.php');
    require('admin/inc/essentials.php');

    require('inc/midtrans/Midtrans.php');

    date_default_timezone_set("Asia/Jakarta");

    session_start();

    if(!(isset($_SESSION['login']) && $_SESSION['login']==true)){
        redirect('index.php');
    }

    if(isset($_POST['pay_now']))
    {
        Config::$serverKey = 'SB-Mid-server-cVWDFZurOiO0YqrkLCKn6qRS';
        Config::$clientKey = 'SB-Mid-client-mtGw2S9jLzeMkWx3';
        // Enable sanitization
        Config::$isSanitized = true;

        // Enable 3D-Secure
        Config::$is3ds = true;
        

        $CUST_ID = $_SESSION['uId'];
        $ORDER_ID =  'ORD_'.$_SESSION['uId'].random_int(11111,9999999);
        $gross_amount = $_SESSION['room']['payment'];


        $transaction_details = array(
            'order_id' => $ORDER_ID,
            'gross_amount' => $_SESSION['room']['payment'], // no decimal allowed for creditcard
        );

        $transaction_data = array(
            'transaction_details' => $transaction_details
          );

        $frm_data = filteration($_POST);

        $query1 = "INSERT INTO `booking_order`(`user_id`, `room_id`, `check_in`,`check_out`, `order_id`) VALUES (?,?,?,?,?)";

        insert($query1,[$CUST_ID,$_SESSION['room']['id'],$frm_data['checkin'],$frm_data['checkout'],$ORDER_ID],'issss');

        $booking_id = mysqli_insert_id($con);

        $query2 = "INSERT INTO `booking_details`(`booking_id`, `room_name`, `price`, `total_pay`,
            `user_name`, `phonenum`, `address`) VALUES (?,?,?,?,?,?,?)";
        
        insert($query2,[$booking_id,$_SESSION['room']['name'],$_SESSION['room']['price'],$gross_amount,$frm_data['name'],
            $frm_data['phonenum'],$frm_data['address']],'issssss');

        try {
            $snap_token = Snap::getSnapToken($transaction_data);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
       
    }
?>

<!DOCTYPE html>
<html>
    <body>
        <button id="pay-button">Pay!</button>
        <pre><div id="result-json">JSON result will appear here after payment:<br></div></pre> 

        <!-- TODO: Remove ".sandbox" from script src URL for production environment. Also input your client key in "data-client-key" -->
        <script src="https://app.sandbox.midtrans.com/snap/snap.js" data-client-key="<?php echo Config::$clientKey;?>"></script>
        <script type="text/javascript">
            document.getElementById('pay-button').onclick = function(){
                // SnapToken acquired from previous step
                snap.pay('<?php echo $snap_token?>', {
                    // Optional
                    onSuccess: function(result){
                        
                        $frm_data = filteration($_POST);

                        $q = "UPDATE `booking_order` SET `transaction_status`='paid' WHERE `order_id`=? ";
                        $values = [$frm_data['transaction_status']];
                        $res = update($q,$values,'ss');
                       
                        /* You may add your own js here, this is just example */ 
                        console.log('success');console.log(result);
                        // document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);
                       
                        
                    },
                    // Optional
                    onPending: function(result){
                        /* You may add your own js here, this is just example */ 
                        // document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);
                        console.log('pending');console.log(result);
                    },
                    // Optional
                    onError: function(result){
                        /* You may add your own js here, this is just example */ 
                        // document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);
                        console.log('error');console.log(result);
                    }
                });
            };
        </script>
    </body>
</html>

~

in_array(): Argument #2 ($haystack) must be of type array

Why am i having an

Type: TypeError
Message: in_array(): Argument #2 ($haystack) must be of type array, int given

my code is something like this hope someone can help i’m using codeigniter 3

<div class="form-group">
<label for="sub_category">Category:</label>
<?php $sub_category_data = json_decode($product_data['sub_category_id']); ?>
<select class="form-control select_group" id="sub_category_1" name="sub_category[]" onchange="getSubCategoryData(1)">
<?php foreach ($sub_category as $k => $v): ?>
<option value="<?php echo $v['id'] ?>" <?php if(in_array($v['id'], $sub_category_data)) { echo 'selected="selected"'; } ?>><?php echo $v['name'] ?></option>
<?php endforeach ?>
</select>
</div>

mailchimp api when moving member to new audience, member is not removed from old audience

When using the Mailchimp 3.0 api, if I move a member to a new list/audience using the ‘add or update list member’ endpoint, the old instance of the member is not removed from the old audience.

First I tried updating a member to a new group using the ‘add or update list member’. This resulted in there being the same member in 2 audiences. Next I tried retrieving all users from the other list, then checking if the user I wanted to add to a new group was found in there. Then remove that user from the old list and add the new member to the right audience. The problem with this is that the old user gets archived and cannot be added back using the same api call as before when the user is changed back to the old audience.

How do I edit the label and x-axis of a laravel/chart.js boxplot?

Chart.js translation for plotting on frontend side in Laravel. There is a yield of 3 months dates and their datas. How should I fit charjs that overlap and not all dates are written at the end of x? (texts are overlapping, i dont want it, and I want all the dates to be on the x-axis, I think chartjs skipped it because couldn’t fit it.) it is important can you contact with me

enter image description here

 var myChart1 = new Chart(ctx1, {
        type: 'bar',
        data: {
                labels: dates,
                datasets: [{
        label: 'BACKLOG ON HOLD INCIDENTS AVG PERFORMANCE- BURSA',
        data: results,
        backgroundColor: [
            'rgba(76, 196, 23, 0.6)'

        ],
        borderColor: [
            'rgba(219, 249, 219, 1)',

        ],
        borderWidth: 1,
                }]
        },
        plugins: [ChartDataLabels],
        options: {
                plugins:{
                legend:{
                        display:true
                },
        datalabels:{
                color:'blue',
                anchor:'end',
        font:{
                weight:'bold',
                size:14
             }
                  }
        },
        scales: {
        y: {
            beginAtZero: true
           }
        },
        animation: {
            duration: 0
        }
        }
    });

Error load Json data array from Php in Python

I have this data of array in php that converted to json

$dataraw = $_SESSION['image'];
$datagambar = json_encode($dataraw);
$escaped_json = escapeshellarg($datagambar);

Escaped_json output as strings:

"[{ FileName : 20221227_202035.jpg , Model : SM-A528B , Longitude :106.904251, Latitude :-6.167665},{ FileName : 20221227_202157.jpg , Model : SM-A528B , Longitude :106.9042428, Latitude :-6.167658099722223}]"

Datagambar output as array :

[{"FileName":"20221227_202035.jpg","Model":"SM-A528B","Longitude":106.904251,"Latitude":-6.167665},{"FileName":"20221227_202157.jpg","Model":"SM-A528B","Longitude":106.9042428,"Latitude":-6.167658099722223}]

I want to call it to python, this is my py code

escaped_json = sys.argv[1] 
parsed_data = json.loads(escaped_json) 
print (parsed_data[0])

But from parsed_data = json.loads(escaped_json)
I get an error JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Is there any suggestions how to fix it?

How to get array from php to react axios?

Array
(
    [0] => Array
        (
            [images] => projects/0mxlk1duzt/1.png
        )

    [1] => Array
        (
            [images] => projects/0mxlk1duzt/2.png
        )

    [2] => Array
        (
            [images] => projects/0mxlk1duzt/3.png
        )
)

this is array what i have in php file on server, code in php

<?php
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
    header("Access-Control-Allow-Headers: Content-Disposition, Content-Type, Content-Length, Accept-Encoding");
    header("Content-type:application/json");

$response = array();
    foreach(glob('projects/0mxlk1duzt/*', GLOB_NOSORT) as $image)   
    {  
                  array_push($response,array(
                    "images" => $image
                  ));
    }  
    print_r($response); 
?>

next i have react app with axios with code:

class Gallery extends React.Component {
  state = {
    images: []
  }
  componentDidMount() {
    const url = 'http://work.eniso.ru/gallery.php'
    axios.get(url).then(response => response.data)
    .then((data) => {
      this.setState({ images: data })
      console.log(this.state.images)
     })
  }
  render(){
    return(
      <div className='gallery'>
        <ul>
          { this.state.images }
        </ul>
      </div>
    )
  }
}

now i can only output this in text format, but i don’t understand how to get array and in react i must do array.map to output elements in

  • Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool given in [duplicate]

    i want to select table with validation with id user

    `

    $id_user_login = $_SESSION['id_user'];        
                                        
    $activity=mysqli_query($con,
    "SELECT * FROM mai_activity
    JOIN mai_user ON mai_activity.id_user = mai_user.id_user
    JOIN mai_corporation ON mai_activity.id_corporation = mai_corporation.id_corporation
    JOIN mai_level_user ON mai_activity.id_level_user = mai_level_user.id_level_user 
    WHERE id_user = '$id_user_login'
    ORDER BY id_activity DESC");
    while ($data=mysqli_fetch_array($activity)){}
    

    `

    I get this error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool given at the while ($data….) statement.