JS regex replace multiple matches

given an JSON object which contains tags identified by {{ I require to find all matches in the payloadand replace them. The following code works, but only returns the 1st match, and if I turn on the gim flags to replace all matches, code breaks. below is what I’ve tried so far, i guess is worth noting the application uses ecma5 engine (SpiderMonkey)

For the sake of demoing, Im using the window variables, as with the application I am working for, I should also be replacing with workflow variables, so works similarly.

var Obj = {
  hostname: "Test 1 {{window.location.hostname}}",
  protocol: "Test 2 {{window.location.protocol}}"
}
var myObj   = JSON.stringify(Obj)
var regex   = /{{window.location.(.+?)}}/       //gmi flag breaks code
var match   = myObj.match(regex)[1];
var enrich  = Function('return '+"window.location."+match)();
var _Obj    = myObj.replace(regex,enrich)


console.log(JSON.parse(_Obj))

Jquery datetimepicker last day of month not working

I have a filter page with 2 datetimepicker as Start date (first day of month) and End date (last day of month). This is what I’m trying to do:

$(document).ready(function () {

    var date = new Date(2025, 3, 22);
    var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
    var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

    console.log("date");
    console.log(date);
    console.log("firstDay");
    console.log(firstDay);
    console.log("lastDay");
    console.log(lastDay);
    
    $('#StartDate').datetimepicker({
        defaultDate: firstDay,
        locale: 'en-ie',
        format: 'DD/MM/YYYY',
        showClose: true,
        showClear: true,
        ignoreReadonly: true,
        minDate: '1900-01-01',
        allowInputToggle: true
    });

    $('#EndDate').datetimepicker({
        defaultDate: lastDay,
        locale: 'en-ie',
        format: 'DD/MM/YYYY',
        showClose: true,
        showClear: true,
        ignoreReadonly: true,
        minDate: '1900-01-01',
        allowInputToggle: true
    });
}

The error:

For example, if the date is 22/04/2025, the firstDay will be 01/04/2025 and the lastDay will be 30/04/2025.
But my datimepickers showing fistDay as 31/03/2025 and lastDay as 29/04/2025.
1 day before the correct dates.
In console log my variables is correct but when I try to query my components value, I see the wrong days.

Console log

Console log variables

I’ve looked in several places and I can’t find the reason for this error.

Do platforms like LeetCode benchmark official solutions to set time limits? [closed]

I’ve heard that platforms like LeetCode (and similar online judges) create an official or optimal solution for each problem and then run it to determine execution time. Based on that, they set the time limit for submissions slightly higher.
Is this accurate?
online-judges
Do platforms actually do this?

Are there any official articles, documentation, or blog posts from LeetCode, Codeforces, HackerRank, etc., that explain this process?

Is it standard practice across most competitive programming platforms?

I’m building a custom judge (similar to Judge0) and want to understand how professionals design fair time limits. Any authoritative reference or practical experience would be appreciated.

When i expand a card in page top part of page becomes inaccessible

<div className="flex flex-col w-4/5 ">
        <button
          onClick={() => {
            setiscardopened(!iscardopened);
          }}
          className="w-full h-11 mt-3 bg-green-500 rounded-xl cursor-pointer"
        ></button>
        {rndnum ? (
          <div
            id="card-container"
            className={
              iscardopened
                ? "flex flex-col justify-center items-center border-2 transition-all duration-500 opacity-100 scale-100  max-h-full h-1/3  overflow-hidden"
                : "flex flex-col justify-center items-center border-2 transition-all    duration-500 opacity-0 scale-95    h-0 overflow-hidden"
            }
          >
            <img
              src={`onlystates/${rndnum[0]}.png`}
              className="border-2 w-auto h-20"
            ></img>
            <div className="flex-row flex">
              <InputandList
                inputref={inputref}
                setquery={setcardquery}
                statenames={CardsNames}
                filterednames={filteredCardNames ? filteredCardNames : [""]}
                widthofinput={"3/4"}
                placeholder={
                  {placeholders}}
              ></InputandList>
              <button
                className=" w-4/11 rounded-2xl mt-2 h-11 text-sm border-5 border-gray-800 bg-gray-700 z-50"
                // onClick={handlesubmit}
              >
                GUESS
              </button>
            </div>
            <CardGuesContainer></CardGuesContainer>
          </div>
        ) : (
          ""
        )}

Page with Card opened

)

page without card opened

tried to add overflow style to parent classes and card’s class but everytime pages top part is becomes inaccessible

How to store data in an array in row/column format using javascript

I am trying to bring all the columns of a table from database and want to store whole data (retrieved from webform) in an array with column names.
For Example Following is my database Table.
StudentName     Roll_No     Subject     Marks
Rock                     101             English      98

I want to store above data in same structure in my array.
Here is my code…

function Insert(FormName, DivName) {
    $.ajax({
        type: "POST",
        url: "" + FormName + ".aspx/GetData",
        data: '{}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var xmlDoc = $.parseXML(response.d);
            var xml = $(xmlDoc);
            var Records = xml.find("Table");
            if (Records.length > 0) {
             
                var DetailData = new Array();  // I want to store table in same structure in this array.
                
                $.each(Records, function () {
                    var record = $(this);
                    var ColName = record.find("Column_name").text();   //Getting Column names from database
                    var ColValue = GetColumnsValue(ColName, DivName);  // getting columns value in webform.

                });
            }
        },
        error: function (d) {
            alert(d.responseText);
        }
    });
}

Vite react failed to import dynamic component in production. just after deployment throwing error once.on refresh error goes way

i am working on vite react project and with ci/cd when i deploy app on server just after that error with message ‘Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “text/html”. Strict MIME type checking is enforced for module scripts per HTML spec.’ comes and with this comes failed to import dynamic component. and on hard refresh this error goes away

Declaring variable in every time when function declaring

Not every time we need the declaration of variables in function that using many time. how to separate the declaration of variables and functions in the time that variables is necessary for functions .

function Help(text, color) {
    var help = document.getElementById("help");
    help.style.color = color;
    help.innerText = text;
}

document.getElementById("button").addEventListener("click", function() {
        Help(Math.floor(Math.random() * 360), ["red", "blue", "white"][Math.floor(Math.random() * 2)]);
});

In this simple example : the variable “help” is declaring every time when i click on button. So this what i no need . I know i can declare this variable like a global variable but that no need also . so can you give me a solution . I believe the solution is to learn the functions__closures. I looked that and i can’t know the solution.

Character replacement loop

I am sharing a piece of code.

const str = "This is very long road"
const newChar = {
  s: "S",
  o: "O"
};

let newStr = "";

for (const char of str){
  newStr += newChar[char] || char;
}
console.log(newStr);

Can someone please explain me what is this code means?

newChar[char] || char

Can’t we just write newChar?

Character Replacement Loop JavaScript

I am sharing a piece of code.

const str = "This is very long road"
const newChar = {
  s: "S",
  o: "O"
};

let newStr = "";

for (const char of str){
  newStr += newChar[char] || char;
}
console.log(newStr);

Can someone please explain me what is this code means?

newChar[char] || char

Can’t we just write newChar?

Converting a d.m.Y string to an SQL date [duplicate]

I have a podata column in an SQL string that says 04.22.2025

I want to convert this string to a date and compare it with today, how do I do this?

$sql_my_date = date('Y-m-d');
CONVERT(DATETIME, podata, 111) >= CAST('$sql_my_date' AS datetime)

does not work

DataTables warning: table id=sales-table – Ajax error. For more information about this error, please see http://datatables.net/tn/7

I am new and i have faced this error on my application. When operate this application on localhost it will works fine but when i try to host this application on domain server it showing me like this error kindly give me a solution so i can do it thanks.

Following are my code

Screenshot 01

Screenshot 02

My Route file code

<?php

use IlluminateSupportFacadesRoute;
use AppHttpControllersHomeController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

Route::get('/', function () {
    return view('auth.login');
})->middleware('guest');

Auth::routes(['register' => false]);

Route::group(['middleware' => 'auth'], function () {
    Route::get('/home', 'HomeController@index')
        ->name('home');

    Route::get('/sales-purchases/chart-data', 'HomeController@salesPurchasesChart')
        ->name('sales-purchases.chart');

    Route::get('/current-month/chart-data', 'HomeController@currentMonthChart')
        ->name('current-month.chart');

    Route::get('/payment-flow/chart-data', 'HomeController@paymentChart')
        ->name('payment-flow.chart');
        // routes/web.php

Route::get('/export-cash-flow-overview', [HomeController::class, 'exportCashFlowOverview'])
->name('exportCashFlowOverview');

});

My Controller file code

 <?php
    
    namespace ModulesSaleHttpControllers;
    
    use ModulesSaleDataTablesSalesDataTable;
    use GloudemansShoppingcartFacadesCart;
    use IlluminateRoutingController;
    use IlluminateSupportFacadesDB;
    use IlluminateSupportFacadesGate;
    use ModulesPeopleEntitiesCustomer;
    use ModulesProductEntitiesProduct;
    use ModulesSaleEntitiesSale;
    use ModulesSaleEntitiesSaleDetails;
    use ModulesSaleEntitiesSalePayment;
    use ModulesSaleHttpRequestsStoreSaleRequest;
    use ModulesSaleHttpRequestsUpdateSaleRequest;
    
    class SaleController extends Controller
    {
    
        public function index(SalesDataTable $dataTable) {
            abort_if(Gate::denies('access_sales'), 403);
    
            return $dataTable->render('sale::index');
        }
    
    
        public function create() {
            abort_if(Gate::denies('create_sales'), 403);
    
            Cart::instance('sale')->destroy();
    
            return view('sale::create');
        }
    
    
        public function store(StoreSaleRequest $request) {
            DB::transaction(function () use ($request) {
                $due_amount = $request->total_amount - $request->paid_amount;
    
                if ($due_amount == $request->total_amount) {
                    $payment_status = 'Unpaid';
                } elseif ($due_amount > 0) {
                    $payment_status = 'Partial';
                } else {
                    $payment_status = 'Paid';
                }
    
                $sale = Sale::create([
                    'date' => $request->date,
                    'customer_id' => $request->customer_id,
                    'customer_name' => Customer::findOrFail($request->customer_id)->customer_name,
                    'tax_percentage' => $request->tax_percentage,
                    'discount_percentage' => $request->discount_percentage,
                    'shipping_amount' => $request->shipping_amount * 100,
                    'paid_amount' => $request->paid_amount * 100,
                    'total_amount' => $request->total_amount * 100,
                    'due_amount' => $due_amount * 100,
                    'status' => $request->status,
                    'payment_status' => $payment_status,
                    'payment_method' => $request->payment_method,
                    'note' => $request->note,
                    'tax_amount' => Cart::instance('sale')->tax() * 100,
                    'discount_amount' => Cart::instance('sale')->discount() * 100,
                ]);
    
                foreach (Cart::instance('sale')->content() as $cart_item) {
                    SaleDetails::create([
                        'sale_id' => $sale->id,
                        'product_id' => $cart_item->id,
                        'product_name' => $cart_item->name,
                        'product_code' => $cart_item->options->code,
                        'quantity' => $cart_item->qty,
                        'price' => $cart_item->price * 100,
                        'unit_price' => $cart_item->options->unit_price * 100,
                        'sub_total' => $cart_item->options->sub_total * 100,
                        'product_discount_amount' => $cart_item->options->product_discount * 100,
                        'product_discount_type' => $cart_item->options->product_discount_type,
                        'product_tax_amount' => $cart_item->options->product_tax * 100,
                    ]);
    
                    if ($request->status == 'Shipped' || $request->status == 'Completed') {
                        $product = Product::findOrFail($cart_item->id);
                        $product->update([
                            'product_quantity' => $product->product_quantity - $cart_item->qty
                        ]);
                    }
                }
    
                Cart::instance('sale')->destroy();
    
                if ($sale->paid_amount > 0) {
                    SalePayment::create([
                        'date' => $request->date,
                        'reference' => 'INV/'.$sale->reference,
                        'amount' => $sale->paid_amount,
                        'sale_id' => $sale->id,
                        'payment_method' => $request->payment_method
                    ]);
                }
            });
    
            toast('Sale Created!', 'success');
    
            return redirect()->route('sales.index');
        }
    
    
        public function show(Sale $sale) {
            abort_if(Gate::denies('show_sales'), 403);
    
            $customer = Customer::findOrFail($sale->customer_id);
    
            return view('sale::show', compact('sale', 'customer'));
        }
    
    
        public function edit(Sale $sale) {
            abort_if(Gate::denies('edit_sales'), 403);
    
            $sale_details = $sale->saleDetails;
    
            Cart::instance('sale')->destroy();
    
            $cart = Cart::instance('sale');
    
            foreach ($sale_details as $sale_detail) {
                $cart->add([
                    'id'      => $sale_detail->product_id,
                    'name'    => $sale_detail->product_name,
                    'qty'     => $sale_detail->quantity,
                    'price'   => $sale_detail->price,
                    'weight'  => 1,
                    'options' => [
                        'product_discount' => $sale_detail->product_discount_amount,
                        'product_discount_type' => $sale_detail->product_discount_type,
                        'sub_total'   => $sale_detail->sub_total,
                        'code'        => $sale_detail->product_code,
                        'stock'       => Product::findOrFail($sale_detail->product_id)->product_quantity,
                        'product_tax' => $sale_detail->product_tax_amount,
                        'unit_price'  => $sale_detail->unit_price
                    ]
                ]);
            }
    
            return view('sale::edit', compact('sale'));
        }
    
    
        public function update(UpdateSaleRequest $request, Sale $sale) {
            DB::transaction(function () use ($request, $sale) {
    
                $due_amount = $request->total_amount - $request->paid_amount;
    
                if ($due_amount == $request->total_amount) {
                    $payment_status = 'Unpaid';
                } elseif ($due_amount > 0) {
                    $payment_status = 'Partial';
                } else {
                    $payment_status = 'Paid';
                }
    
                foreach ($sale->saleDetails as $sale_detail) {
                    if ($sale->status == 'Shipped' || $sale->status == 'Completed') {
                        $product = Product::findOrFail($sale_detail->product_id);
                        $product->update([
                            'product_quantity' => $product->product_quantity + $sale_detail->quantity
                        ]);
                    }
                    $sale_detail->delete();
                }
    
                $sale->update([
                    'date' => $request->date,
                    'reference' => $request->reference,
                    'customer_id' => $request->customer_id,
                    'customer_name' => Customer::findOrFail($request->customer_id)->customer_name,
                    'tax_percentage' => $request->tax_percentage,
                    'discount_percentage' => $request->discount_percentage,
                    'shipping_amount' => $request->shipping_amount * 100,
                    'paid_amount' => $request->paid_amount * 100,
                    'total_amount' => $request->total_amount * 100,
                    'due_amount' => $due_amount * 100,
                    'status' => $request->status,
                    'payment_status' => $payment_status,
                    'payment_method' => $request->payment_method,
                    'note' => $request->note,
                    'tax_amount' => Cart::instance('sale')->tax() * 100,
                    'discount_amount' => Cart::instance('sale')->discount() * 100,
                ]);
    
                foreach (Cart::instance('sale')->content() as $cart_item) {
                    SaleDetails::create([
                        'sale_id' => $sale->id,
                        'product_id' => $cart_item->id,
                        'product_name' => $cart_item->name,
                        'product_code' => $cart_item->options->code,
                        'quantity' => $cart_item->qty,
                        'price' => $cart_item->price * 100,
                        'unit_price' => $cart_item->options->unit_price * 100,
                        'sub_total' => $cart_item->options->sub_total * 100,
                        'product_discount_amount' => $cart_item->options->product_discount * 100,
                        'product_discount_type' => $cart_item->options->product_discount_type,
                        'product_tax_amount' => $cart_item->options->product_tax * 100,
                    ]);
    
                    if ($request->status == 'Shipped' || $request->status == 'Completed') {
                        $product = Product::findOrFail($cart_item->id);
                        $product->update([
                            'product_quantity' => $product->product_quantity - $cart_item->qty
                        ]);
                    }
                }
    
                Cart::instance('sale')->destroy();
            });
    
            toast('Sale Updated!', 'info');
    
            return redirect()->route('sales.index');
        }
    
    
        public function destroy(Sale $sale) {
            abort_if(Gate::denies('delete_sales'), 403);
    
            $sale->delete();
    
            toast('Sale Deleted!', 'warning');
    
            return redirect()->route('sales.index');
        }
    }
    

    My SalesDataTable.php


<?php

namespace ModulesSaleDataTables;

use ModulesSaleEntitiesSale;
use YajraDataTablesHtmlButton;
use YajraDataTablesHtmlColumn;
use YajraDataTablesHtmlEditorEditor;
use YajraDataTablesHtmlEditorFields;
use YajraDataTablesServicesDataTable;

class SalesDataTable extends DataTable
{

    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
            ->addColumn('total_amount', function ($data) {
                return format_currency($data->total_amount);
            })
            ->addColumn('paid_amount', function ($data) {
                return format_currency($data->paid_amount);
            })
            ->addColumn('due_amount', function ($data) {
                return format_currency($data->due_amount);
            })
            ->addColumn('status', function ($data) {
                return view('sale::partials.status', compact('data'));
            })
            ->addColumn('payment_status', function ($data) {
                return view('sale::partials.payment-status', compact('data'));
            })
            ->addColumn('action', function ($data) {
                return view('sale::partials.actions', compact('data'));
            });
    }

    public function query(Sale $model)
    {
        return $model->newQuery();
    }

    public function html()
    {
        return $this->builder()
            ->setTableId('sales-table')
            ->columns($this->getColumns())
            ->minifiedAjax()
            ->dom("<'row'<'col-md-3'l><'col-md-5 mb-2'B><'col-md-4'f>> .
                                'tr' .
                                <'row'<'col-md-5'i><'col-md-7 mt-2'p>>")
            ->orderBy(8)
            ->buttons(
                Button::make('excel')
                    ->text('<i class="bi bi-file-earmark-excel-fill"></i> Excel'),
                Button::make('print')
                    ->text('<i class="bi bi-printer-fill"></i> Print'),
                Button::make('reset')
                    ->text('<i class="bi bi-x-circle"></i> Reset'),
                Button::make('reload')
                    ->text('<i class="bi bi-arrow-repeat"></i> Reload')
            );
    }

    protected function getColumns()
    {
        return [
            Column::make('reference')
                ->className('text-center align-middle'),

            Column::make('date')
                ->className('text-center align-left'),

            Column::make('customer_name')
                ->title('Customer')
                ->className('text-center align-middle'),

            // Column::computed('status')
            //     ->className('text-center align-middle'),

            Column::computed('total_amount')
                ->className('text-center align-middle'),

            Column::computed('paid_amount')
                ->className('text-center align-middle'),

            Column::computed('due_amount')
                ->className('text-center align-middle'),

            Column::computed('payment_status')
                ->className('text-center align-middle'),

            Column::computed('action')
                ->exportable(false)
                ->printable(false)
                ->className('text-center align-middle'),

            Column::make('created_at')
                ->visible(false)
        ];
    }

    protected function filename()
    {
        return 'Sales_' . date('YmdHis');
    }
}
 
      

MY Model file code

<?php

namespace ModulesSaleEntities;

use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentFactoriesHasFactory;

class Sale extends Model
{
    use HasFactory;

    protected $guarded = [];

    public function saleDetails() {
        return $this->hasMany(SaleDetails::class, 'sale_id', 'id');
    }

    public function salePayments() {
        return $this->hasMany(SalePayment::class, 'sale_id', 'id');
    }

    public static function boot() {
        parent::boot();

        static::creating(function ($model) {
            $number = Sale::max('id') + 1;
            $model->reference = make_reference_id('SL', $number);
        });
    }

    public function scopeCompleted($query) {
        return $query->where('status', 'Completed');
    }

    public function getShippingAmountAttribute($value) {
        return $value / 100;
    }

    public function getPaidAmountAttribute($value) {
        return $value / 100;
    }

    public function getTotalAmountAttribute($value) {
        return $value / 100;
    }

    public function getDueAmountAttribute($value) {
        return $value / 100;
    }

    public function getTaxAmountAttribute($value) {
        return $value / 100;
    }

    public function getDiscountAmountAttribute($value) {
        return $value / 100;
    }
}

MY View Resource file code

@extends('layouts.app')

@section('title', 'Sales')

@section('third_party_stylesheets')
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.25/css/dataTables.bootstrap4.min.css">
@endsection

@section('breadcrumb')
    <ol class="breadcrumb border-0 m-0">
        <li class="breadcrumb-item"><a href="{{ route('home') }}">Home</a></li>
        <li class="breadcrumb-item active">Sales</li>
    </ol>
@endsection

@section('content')
    <div class="container-fluid">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="card-body">
                        <a href="{{ route('sales.create') }}" class="btn btn-primary">
                            Add Sale <i class="bi bi-plus"></i>
                        </a>

                        <hr>

                        <div class="table-responsive">
                            {!! $dataTable->table() !!}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

@push('page_scripts')
    {!! $dataTable->scripts() !!}
@endpush

GCP app sometimes losing session data after post

Starting some time yesterday afternoon, my PHP app hosted on GCP using App Engine sometimes (but not always) loses session data on submit. I’m using the following at the top of each page to handle POST data:

//if data passed via post, put it in session and reload page
if (isset($_POST['form_data'])) {
    $_SESSION['form_data'] = $dp->clean_input_data($_POST['form_data']);
    $_SESSION['action'] = 'submit';
    header("location: ".$_SERVER['REQUEST_URI']);
    die();
}

So every submit is effectively a redirect back to the same page. I have the same problem if I put data in $_SESSION and redirect to a different page. This has worked flawlessly for literally years…until yesterday. I have verified that the session exists and the session id is not changing. Sometimes it works fine but requires several tries. It is the same on a page that simply refreshes after changing a menu item vs one that accepts form data. I feel like something must have changed on the server side but am at a loss as to what it could be. AND I can’t seem to upgrade my GCP support to reach someone there.

Any ideas?

I am getting an error can someone help me with the api? [closed]

The service is checking and showing the stock but the number is not being purchased, where am I making a mistake?
Can you help me with this? Some people say parentheses but I don’t understand.

<?php

defined('BASEPATH') OR exit('No direct script access allowed');



class Fivesim_Api {

    function get_balance() {

        $api_key = get_instance()->config->item("fivesim_api_key");

        return explode(":",file_get_contents("http://api2.5sim.net/stubs/handler_api.php?api_key={$api_key}&action=getBalance"))[1];

    }

    public function get_number($country, $service) {

        $api_key = get_instance()->config->item("fivesim_api_key");

        $op = array_keys($this->get_cheapest($country,$service))[0];

        $res = file_get_contents("http://api2.5sim.net/stubs/handler_api.php?api_key={$api_key}&action=getNumber&operator={$op}&country={$country}&service={$service}");

        $data = explode(":", $res);

        if(count($data) != 3) {

            $error_code = 400;

            if($res == "NO_NUMBER") $error_code = 103;

            return array(

                "id" => 0,

                "number" => null,

                "error_code" => $error_code

            );

        }

        else {

            file_get_contents("http://api2.5sim.net/stubs/handler_api.php?api_key={$api_key}&action=setStatus&id={$data[1]}&status=1");

            return array(

                "id" => (int)$data[1],

                "number" => $data[2],

                "error_code" => 200

            );

        }

    }

    public function get_message($id) {

        $api_key = get_instance()->config->item("fivesim_api_key");

        $res = file_get_contents("http://api2.5sim.net/stubs/handler_api.php?api_key={$api_key}&action=getStatus&id={$id}");

        $data = explode(":", $res);

        if(count($data) > 1) {

            array_shift($data);

            file_get_contents("http://api2.5sim.net/stubs/handler_api.php?api_key={$api_key}&action=setStatus&id={$id}&status=6");

            return array(

                "code" => join(':', $data)

            );

        }

        else {

            return array(

                "code" => null

            );

        }

    }

    public function get_service_stock($country, $service) {

        $json = json_decode(file_get_contents("https://5sim.net/v1/guest/products/{$country}/any"), true);

        $json_service = $json[$service];

        return $json_service["Qty"];

    }

    public function get_countries() {

        $countries = array();

        $json = json_decode(file_get_contents("https://5sim.net/v1/guest/countries"), true);

        foreach(array_keys($json) as $country) {

            array_push($countries, array("id" => $country, "name" => $country));

        }

        return $countries;

    }

     public function get_countries_new() {

        $countries = array();

        $tr = array(

            "any" => "any",

            //"afghanistan" => "Afganistan",

            "albania" => "Arnavutluk",

            "algeria" => "Cezayir",

            "angola" => "Angola",

            "antiguaandbarbuda" => "Antigua ve Barbuda",

            "argentina" => "Arjantin",

            "armenia" => "Ermenistan",

            "austria" => "Avusturya",

            "azerbaijan" => "Azerbaycan",

            "bahrain" => "Bahreyn",

            "bangladesh" => "Bangladeş",

            "barbados" => "Barbados",

            "belarus" => "Belarus",

            "benin" => "Benin",

            "bhutane" => "Butan",

            "bih" => "Bosna Hersek",

            "bolivia" => "Bolivya",

            "botswana" => "Botsvana",

            "brazil" => "Brezilya",

            "bulgaria" => "Bulgaristan",

            "burkinafaso" => "Burkina Faso",

            "burundi" => "Burundi",

            "cambodia" => "Kamboçya",

            "cameroon" => "Kamerun",

            "canada" => "Kanada",

            "caymanislands" => "Cayman Adaları",

            "chad" => "Çad",

            "colombia" => "Kolombiya",

            "congo" => "Kongo",

            "costarica" => "Kosto Rika",

            "croatia" => "Hırvatistan",

            "cyprus" => "Kıbrıs",

            "czech" => "Çekya",

            "djibouti" => "Cibuti",

            "dominicana" => "Dominik Cumhuriyeti",

            "easrrimor" => "Doğu Timor",

            "ekvador" => "Ekvador",

            "egpty" => "Mısır",

            "englad" => "İngiltere",

            "equatorialguinea" => "Ekvator Ginesi",

            "estonia" => "Estonya",

            "ethiopia" => "Etiyopya",

            "finland" => "Finlandiya",

            "france" => "Fransa",

            "frenchguiana" => "Fransız Guyanası",

            "gabon" => "Gabon",

            "gambia" => "Gambiya",

            "georgia" => "Gürcistan",

            "germany" => "Almanya",

            "ghana" => "Gana",

            "guadeloupe" => "Guadeloupe",

            "guatemala" => "Guatemala",

            "guinea" => "Gine",

            "guineabissau" => "Gine-Bissau",

            "guyana" => "Guyana",

            "haiti" => "Haiti",

            "honduras" => "Honduras",

            "hungary" => "Macaristan",

            "india" => "Hindistan",

            "indonesia" => "Endonezya",

            "iran" => "İran",

            "iraq" => "Irak",

            "ireland" => "İrlanda",

            "israel" => "İsrail",

            "italy" => "İtalya",

            "djibouti" => "Cibuti",

            "ivorycoast" => "Fildişi Sahili",

            "jamaica" => "Jamaika",

            "jordan" => "Ürdün",

            "kazakhstan" => "Kazakistan",

            "kenya" => "Kenya",

            "kuwait" => "Kuveyt",

            "laos" => "Laos",

            "latvia" => "Letonya",

            "lesotho" => "Lesotho",

            "libya" => "Libya",

            "lithuania" => "Litvanya",

            "luxembourg" => "Lüksemburg",

            "macau" => "Makao",

            "madagascar" => "Madagaskar",

            "malawi" => "Malavi",

            "malaysia" => "Malezya",

            "maldives" => "Maldivler",

            "mali" => "Mali",

            "mauritania" => "Moritanya",

            "mauritius" => "Mauritius",

            "mexico" => "Meksika",

            "moldova" => "Moldova",

            "mongolia" => "Moğolistan",

            "montenegro" => "Karadağ",

            "morocco" => "Fas",

            "mozambique" => "Mozambik",

            "myanmar" => "Myanmar",

            "namibia" => "Namibya",

            "nepal" => "Nepal",

            "netherlands" => "Hollanda",

            "newzealand" => "Yeni Zelanda",

            "nicaragua" => "Nikaragua",

            "nigeria" => "Nijerya",

            "oman" => "Umman",

            "pakistan" => "Pakistan",

            "panama" => "Panama",

            "papuanewguinea" => "Papua Yeni Gine",

            "paraguay" => "Paraguay",

            "peru" => "Peru",

            "philippines" => "Filipinler",

            "poland" => "Polonya",

            "portugal" => "Portekiz",

            "puertorico" => "Porto Riko",

            "qatar" => "Katar",

            "reunion" => "Réunion",

            "romania" => "Romanya",

            "russia" => "Rusya",

            "rwanda" => "Ruanda",

            "saintkittsandnevis" => "Saint Kitts ve Nevis",

            "saintlucia" => "Saint Lucia",

            "saintvincentandgrenadines" => "Saint Vincent ve Grenadinler",

            "salvador" => "Salvador",

            "saudiarabia" => "Suudi Arabistan",

            "senegal" => "Senegal",

            "serbia" => "Sırbistan",

            "slovakia" => "Slovakya",

            "slovenia" => "Slovenya",

            "somalia" => "Somali",

            "southafrica" => "Güney Afrika",

            "spain" => "İspanya",

            "srilanka" => "Sri Lanka",

            "sudan" => "Sudan",

            "suriname" => "Surinam",

            "swaziland" => "Esvati̇ni̇",

            "sweden" => "İsveç",

            "syria" => "Suriye",

            "taiwan" => "Tayvan",

            "tajikistan" => "Tacikistan",

            "tanzania" => "Tanzanya",

            "thailand" => "Tayland",

            "trinidad and tobago" => "Trinidad ve Tobago",

            "togo" => "Togo",

            "tunisia" => "Tunus",

            "turkey" => "Türkiye",

            "turkmenistan" => "Türkmenistan",

            "uae" => "Birleşik Arap Emirlikleri",

            "uganda" => "Uganda",

            "uruguay" => "Uruguay",

            "ukraine" => "Ukrayna",

            "usa" => "Amerika",

            "uzbekistan" => "Özbekistan",

            "venezuela" => "Venezuela",

            "vietnam" => "Vietnam",

            "yemen" => "Yemen",

            "zambia" => "Zambiya",

            "zimbabwe" => "Zimbabve"

        );

        $json = json_decode(file_get_contents("https://5sim.net/v1/guest/countries"), true);

        foreach ($json as $c => $ct){

            if ($c !== "zimbabve")

         {

            array_push($countries, array(
                "name" => isset($tr[$c]) ? $tr[$c] : $ct["text_en"],
                "code" => $c,
                "isInBulk" => isset($tr[$c])
            ));

         }

        }

        return $countries;

    }





    public function get_cheapest($country, $service) {

        $ci =& get_instance();



        $ci->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));



        $key = "$country-$service";

        if (!$cheap = $ci->cache->get($key)) {

            $json = json_decode(file_get_contents("https://5sim.net/v1/guest/prices?country=$country&product=$service"),true);

            $arr = array();

            foreach ($json[$country][$service] as $operator => $data){

                if($data["count"] > 8){

                    array_push($arr, array(

                        $operator => $data["cost"]

                    ));

                }

            }



            usort($arr, function($a,$b){

                return array_values($a)[0] > array_values($b)[0];

            });

            $cheap = $arr[0];

            $ci->cache->save($key,$arr[0] , 900);



        }



        return $cheap;

    }



    public function get_service_price($country, $service) {

        $json = json_decode(file_get_contents("https://5sim.net/v1/guest/prices?country=$country&product=$product"), true);

        return max(array_column($json[$country][$service], 'cost')) . " RUB";

    }

    public function get_services_by_country($country) {

        $services = array();

        $api_key = get_instance()->config->item("fivesim_api_key");

        $json = json_decode(file_get_contents("http://api1.5sim.net/stubs/handler_api.php?api_key=$api_key&action=getNumbersStatus&country=$country"), true);

        foreach(array_keys($json) as $service) {

            if(strlen(explode("_",$service)[0]) > 2) {

                array_push($services, array(

                    "id" => explode("_",$service)[0],

                    "name" => explode("_",$service)[0])

                );

            }

        }

        return $services;

    }

    public function cancel_number($number_id) {

        $api_key = get_instance()->config->item("fivesim_api_key");

        file_get_contents("http://api2.5sim.net/stubs/handler_api.php?api_key={$api_key}&action=setStatus&id={$number_id}&status=-1");

    }

}

?>

The service is checking and showing the stock but the number is not being purchased, where am I making a mistake?
Can you help me with this? Some people say parentheses but I don’t understand.

Get last value of a sub-node in XML parsed by PHP into an array

I am trying to parse an Atom XML feed using PHP. It is for an ebook publisher. All is well, except I cannot work out how to extract the last “subject” tag for each entry: that is the publisher’s tag (instead of Library of Congress subject heading = LCSH), and there are a variable number of those for each title.

Here’s some sample code, and what I’ve got so far:

Feed XML (slightly abbreviated; three book’s worth)

<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="https://standardebooks.org/feeds/atom/style" type="text/xsl"?>
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/">
    <id>https://standardebooks.org/feeds/atom/new-releases</id>
    <link href="https://standardebooks.org/feeds/atom/new-releases" rel="self" type="application/atom+xml"/>
    <title>Standard Ebooks - Newest Ebooks</title>
    <subtitle>The 15 latest Standard Ebooks, most-recently-released first.</subtitle>
    <icon>https://standardebooks.org/images/logo.png</icon>
    <updated>2025-04-29T17:50:47Z</updated>
    <author>
        <name>Standard Ebooks</name>
        <uri>https://standardebooks.org</uri>
    </author>
    <link href="https://standardebooks.org/opensearch" rel="search" title="Standard Ebooks" type="application/opensearchdescription+xml"/>
    <entry>
        <id>https://standardebooks.org/ebooks/anthony-berkeley/the-poisoned-chocolates-case</id>
        <title>The Poisoned Chocolates Case</title>
        <author>
            <name>Anthony Berkeley</name>
            <uri>https://standardebooks.org/ebooks/anthony-berkeley</uri>
        </author>
        <published>2025-04-21T03:39:39Z</published>
        <updated>2025-04-21T09:01:35Z</updated>
        <rights>Public domain in the United States. Users located outside of the United States must check their local laws before using this ebook. Original content released to the public domain via the Creative Commons CC0 1.0 Universal Public Domain Dedication.</rights>
        <summary type="text">A club of amateur sleuths attempts to solve a crime whose solution has eluded Scotland Yard.</summary>
        <category scheme="http://purl.org/dc/terms/LCSH" term="Detective and mystery stories"/>
        <category scheme="http://purl.org/dc/terms/LCSH" term="London (England) -- Fiction"/>
        <category scheme="http://purl.org/dc/terms/LCSH" term="Sheringham, Roger (Fictitious character) -- Fiction"/>
        <category scheme="http://purl.org/dc/terms/LCSH" term="Police -- England -- London -- Fiction"/>
        <category scheme="https://standardebooks.org/vocab/subjects" term="Fiction"/>
        <category scheme="https://standardebooks.org/vocab/subjects" term="Mystery"/>
    </entry>
    <entry>
        <id>https://standardebooks.org/ebooks/g-k-chesterton/whats-wrong-with-the-world</id>
        <title>What’s Wrong with the World</title>
        <author>
            <name>G. K. Chesterton</name>
            <uri>https://standardebooks.org/ebooks/g-k-chesterton</uri>
        </author>
        <published>2025-04-29T03:11:02Z</published>
        <updated>2025-04-29T03:11:05Z</updated>
        <rights>Public domain in the United States. Users located outside of the United States must check their local laws before using this ebook. Original content released to the public domain via the Creative Commons CC0 1.0 Universal Public Domain Dedication.</rights>
        <summary type="text">Philosopher G. K. Chesterton comments on various social issues of his day, including property, imperialism, feminism, and education.</summary>
        <category scheme="http://purl.org/dc/terms/LCSH" term="Social problems"/>
        <category scheme="https://standardebooks.org/vocab/subjects" term="Nonfiction"/>
        <category scheme="https://standardebooks.org/vocab/subjects" term="Philosophy"/>
    </entry>
    <entry>
        <id>https://standardebooks.org/ebooks/george-gissing/the-private-papers-of-henry-ryecroft</id>
        <title>The Private Papers of Henry Ryecroft</title>
        <author>
            <name>George Gissing</name>
            <uri>https://standardebooks.org/ebooks/george-gissing</uri>
        </author>
        <published>2025-04-29T17:21:20Z</published>
        <updated>2025-04-29T17:49:20Z</updated>
        <rights>Public domain in the United States. Users located outside of the United States must check their local laws before using this ebook. Original content released to the public domain via the Creative Commons CC0 1.0 Universal Public Domain Dedication.</rights>
        <summary type="text">A retired Englishman muses on life and literature in his private diary.</summary>
        <category scheme="http://purl.org/dc/terms/LCSH" term="English fiction -- 19th century"/>
        <category scheme="https://standardebooks.org/vocab/subjects" term="Fiction"/>
    </entry>
</feed>

PHP code

<?php 
echo "<ol>". PHP_EOL;
$url = 'atom-sample.xml';

$xmla = simplexml_load_file($url);
  $xml = array();
  foreach($xmla->entry as $node) {
    $xml[] = $node;
  }

foreach($xml as $entry){
  $entry->registerXPathNamespace('ns','http://www.w3.org/2005/Atom');
  echo '<li>'.$entry->author->name .', <i>'. $entry->title .'</i> | '. $entry->category['term'] .'</li>'; 
  }
echo "</ol>";
?>

Parsed array (output of print_r($xml))

Array
(
    [0] => SimpleXMLElement Object
        (
            [id] => https://standardebooks.org/ebooks/anthony-berkeley/the-poisoned-chocolates-case
            [title] => The Poisoned Chocolates Case
            [author] => SimpleXMLElement Object
                (
                    [name] => Anthony Berkeley
                    [uri] => https://standardebooks.org/ebooks/anthony-berkeley
                )

            [published] => 2025-04-21T03:39:39Z
            [updated] => 2025-04-21T09:01:35Z
            [rights] => Public domain in the United States. Users located outside of the United States must check their local laws before using this ebook. Original content released to the public domain via the Creative Commons CC0 1.0 Universal Public Domain Dedication.
            [summary] => A club of amateur sleuths attempts to solve a crime whose solution has eluded Scotland Yard.
            [category] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => http://purl.org/dc/terms/LCSH
                                    [term] => Detective and mystery stories
                                )

                        )

                    [1] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => http://purl.org/dc/terms/LCSH
                                    [term] => London (England) -- Fiction
                                )

                        )

                    [2] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => http://purl.org/dc/terms/LCSH
                                    [term] => Sheringham, Roger (Fictitious character) -- Fiction
                                )

                        )

                    [3] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => http://purl.org/dc/terms/LCSH
                                    [term] => Police -- England -- London -- Fiction
                                )

                        )

                    [4] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => https://standardebooks.org/vocab/subjects
                                    [term] => Fiction
                                )

                        )

                    [5] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => https://standardebooks.org/vocab/subjects
                                    [term] => Mystery
                                )

                        )

                )

        )

    [1] => SimpleXMLElement Object
        (
            [id] => https://standardebooks.org/ebooks/g-k-chesterton/whats-wrong-with-the-world
            [title] => What’s Wrong with the World
            [author] => SimpleXMLElement Object
                (
                    [name] => G. K. Chesterton
                    [uri] => https://standardebooks.org/ebooks/g-k-chesterton
                )

            [published] => 2025-04-29T03:11:02Z
            [updated] => 2025-04-29T03:11:05Z
            [rights] => Public domain in the United States. Users located outside of the United States must check their local laws before using this ebook. Original content released to the public domain via the Creative Commons CC0 1.0 Universal Public Domain Dedication.
            [summary] => Philosopher G. K. Chesterton comments on various social issues of his day, including property, imperialism, feminism, and education.
            [category] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => http://purl.org/dc/terms/LCSH
                                    [term] => Social problems
                                )

                        )

                    [1] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => https://standardebooks.org/vocab/subjects
                                    [term] => Nonfiction
                                )

                        )

                    [2] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => https://standardebooks.org/vocab/subjects
                                    [term] => Philosophy
                                )

                        )

                )

        )

    [2] => SimpleXMLElement Object
        (
            [id] => https://standardebooks.org/ebooks/george-gissing/the-private-papers-of-henry-ryecroft
            [title] => The Private Papers of Henry Ryecroft
            [author] => SimpleXMLElement Object
                (
                    [name] => George Gissing
                    [uri] => https://standardebooks.org/ebooks/george-gissing
                )

            [published] => 2025-04-29T17:21:20Z
            [updated] => 2025-04-29T17:49:20Z
            [rights] => Public domain in the United States. Users located outside of the United States must check their local laws before using this ebook. Original content released to the public domain via the Creative Commons CC0 1.0 Universal Public Domain Dedication.
            [summary] => A retired Englishman muses on life and literature in his private diary.
            [category] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => http://purl.org/dc/terms/LCSH
                                    [term] => English fiction -- 19th century
                                )

                        )

                    [1] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [scheme] => https://standardebooks.org/vocab/subjects
                                    [term] => Fiction
                                )

                        )

                )

        )

)

Output

<ol>
    <li>
        Anthony Berkeley,
        <i>The Poisoned Chocolates Case</i>
        | Detective and mystery stories
    </li>
    <li>
        G. K. Chesterton,
        <i>What’s Wrong with the World</i>
        | Social problems
    </li>
    <li>
        George Gissing,
        <i>The Private Papers of Henry Ryecroft</i>
        | English fiction -- 19th century
    </li>
</ol>

The value I’m after is the last one under [category], which is [5] for the first book, [2] for the second book, and [1] for the third book. Above, I’ve used $entry->category['term'] for this “slot”, which always returns the [0] value—but I want the last one, which is not consistent!

I am aware of the [last()] construct, but no permutation of my code using [last()] has worked. Obviously I’m doing something wrong in handling that sub-array with my approach/code. So what works?! Thanks!