Home > front end >  What's the best way to count the number of occurrences in this json string in PHP
What's the best way to count the number of occurrences in this json string in PHP

Time:09-23

When I request the amount of invoices at Stripe via their API, I get all data returned. So I need to count the number of invoices myself.

This is the JSON data I get back:

{
  "object": "list",
  "data": [
    {
      "id": "in_0LkpzOCKEf7***t2FwMlp5kQ",
      "object": "invoice",
      "account_country": "NL",
      "account_name": "My Business Inc.",
      "account_tax_ids": null,
      "amount_due": 3700,
      "amount_paid": 3700,
      "amount_remaining": 0,
      "application": null,
      "application_fee": null,
      "attempt_count": 1,
      "attempted": true,
      "auto_advance": false,
      "automatic_tax": {
        "enabled": false,
        "status": null
      },
      "billing": "charge_automatically",
      "billing_reason": "subscription_cycle",
      "charge": "ch_2Lkq37CKEf***bt21g0bkJVa",
      "closed": true,
      "collection_method": "charge_automatically",
      "created": 1666436458,
      "currency": "usd",
      "custom_fields": null,
      "customer": "cus_MTkibG***56Uz4",
      "customer_address": {
        "city": "",
        "country": "US",
        "line1": "",
        "line2": "",
        "postal_code": "",
        "state": ""
      },
      "customer_email": "test1@***.net",
      "customer_name": "Test",
      "customer_phone": null,
      "customer_shipping": null,
      "customer_tax_exempt": "none",
      "customer_tax_ids": [],
      "date": 1666436458,
      "default_payment_method": null,
      "default_source": null,
      "default_tax_rates": [],
      "description": null,
      "discount": null,
      "discounts": [],
      "due_date": null,
      "ending_balance": 0,
      "finalized_at": 1666440058,
      "footer": null,
      "forgiven": false,
      "from_invoice": null,
      "hosted_invoice_url": "https://invoice.stripe.com/i/acct_1mMtCKEf7b***2BIJNR2/test_YWNjdF8xbU10Q0t***diTmJ0MkJJSk5SMixfTVRuYWhHcUd5YkNrdkFrSWJTU1BrTFFqWFNLa2NpUiw1NDM5ODkwNw0200PuDmVCv2?s=ap",
      "invoice_pdf": "https://pay.stripe.com/invoice/acct_1mMtCKEf7bNbt2BI***/test_YWNjdF8xbU10Q0tFZjdiTmJ0MkJJSk5SMixfTVRuYWhHcUd5YkNrdkFrSWJTU1BrTFFqWFNLa2NpUiw1NDM5ODkwNw***0PuDmVCv2/pdf?s=ap",
      "last_finalization_error": null,
      "latest_revision": null,
      "lines": {
        "object": "list",
        "data": [
          {
            "id": "sub_0LknEJCKEf7bN***bblGV2Lb",
            "object": "line_item",
            "amount": 3700,
            "amount_excluding_tax": 3700,
            "currency": "usd",
            "description": null,
            "discount_amounts": [],
            "discountable": true,
            "discounts": [],
            "livemode": false,
            "metadata": {},
            "period": {
              "end": 1669114858,
              "start": 1666436458
            },
            "plan": {
              "id": "plan_MTjYr***qiEqvG",
              "object": "plan",
              "active": true,
              "aggregate_usage": null,
              "amount": 3700,
              "amount_decimal": "3700",
              "billing_scheme": "per_unit",
              "created": 1663840359,
              "currency": "usd",
              "interval": "month",
              "interval_count": 1,
              "livemode": false,
              "metadata": {},
              "name": "PrimaJust Basic - Normal (normal)",
              "nickname": null,
              "product": "prod_MTjYz***ireFSm",
              "statement_descriptor": null,
              "tiers": null,
              "tiers_mode": null,
              "transform_usage": null,
              "trial_period_days": null,
              "usage_type": "licensed"
            },
            "price": {
              "id": "plan_MTjYri****EqvG",
              "object": "price",
              "active": true,
              "billing_scheme": "per_unit",
              "created": 1663840359,
              "currency": "usd",
              "custom_unit_amount": null,
              "livemode": false,
              "lookup_key": null,
              "metadata": {},
              "nickname": null,
              "product": "prod_MTjYzrt****FSm",
              "recurring": {
                "aggregate_usage": null,
                "interval": "month",
                "interval_count": 1,
                "trial_period_days": null,
                "usage_type": "licensed"
              },
              "tax_behavior": "unspecified",
              "tiers_mode": null,
              "transform_quantity": null,
              "type": "recurring",
              "unit_amount": 3700,
              "unit_amount_decimal": "3700"
            },
            "proration": false,
            "proration_details": {
              "credited_items": null
            },
            "quantity": 1,
            "subscription": null,
            "subscription_item": "si_MTkjw****365QO",
            "tax_amounts": [],
            "tax_rates": [],
            "type": "subscription",
            "unique_id": "il_0LvfRmCKEf7b****W02LkMli",
            "unique_line_item_id": "sli_09f50cCKE****bt2a5104f59",
            "unit_amount_excluding_tax": "3700"
          }
        ],
        "has_more": false,
        "total_count": 1,
        "url": "/v1/invoices/in_0LkpzOCKEf7bNbt****p5kQ/lines"
      },
      "livemode": false,
      "metadata": {},
      "next_payment_attempt": null,
      "number": "77EC823A-0002",
      "on_behalf_of": null,
      "paid": true,
      "paid_out_of_band": false,
      "payment": "ch_2Lkq37CKEf7bNb****0bkJVa",
      "payment_intent": "pi_2Lkq37CKEf7****21k1FnV1V",
      "payment_settings": {
        "default_mandate": null,
        "payment_method_options": null,
        "payment_method_types": null
      },
      "period_end": 1666436458,
      "period_start": 1663844458,
      "post_payment_credit_notes_amount": 0,
      "pre_payment_credit_notes_amount": 0,
      "quote": null,
      "receipt_number": null,
      "rendering_options": null,
      "starting_balance": 0,
      "statement_descriptor": null,
      "status": "paid",
      "status_transitions": {
        "finalized_at": 1666440058,
        "marked_uncollectible_at": null,
        "paid_at": 1666440058,
        "voided_at": null
      },
      "subscription": "sub_0LknEJCKEf7bN****blGV2Lb",
      "subtotal": 3700,
      "subtotal_excluding_tax": 3700,
      "tax": null,
      "tax_percent": null,
      "test_clock": "clock_0LknBQCKEf7b****4PjP6QSa",
      "total": 3700,
      "total_discount_amounts": [],
      "total_excluding_tax": 3700,
      "total_tax_amounts": [],
      "transfer_data": null,
      "webhooks_delivered_at": 1666436458
    },
    {
      "id": "in_0LknEJCKEf7b*****uRU4Rxf",
      "object": "invoice",
      "account_country": "NL",
      "account_name": "My Business Inc.",
      "account_tax_ids": null,
      "amount_due": 3700,
      "amount_paid": 3700,
      "amount_remaining": 0,
      "application": null,
      "application_fee": null,
      "attempt_count": 1,
      "attempted": true,
      "auto_advance": false,
      "automatic_tax": {
        "enabled": false,
        "status": null
      },
      "billing": "charge_automatically",
      "billing_reason": "subscription_update",
      "charge": "ch_2LknEJCKEf7b****1V5n5Yvt",
      "closed": true,
      "collection_method": "charge_automatically",
      "created": 1663844458,
      "currency": "usd",
      "custom_fields": null,
      "customer": "cus_MTkib****56Uz4",
      "customer_address": {
        "city": "",
        "country": "US",
        "line1": "",
        "line2": "",
        "postal_code": "",
        "state": ""
      },
      "customer_email": "test1@****.net",
      "customer_name": "Test1",
      "customer_phone": null,
      "customer_shipping": null,
      "customer_tax_exempt": "none",
      "customer_tax_ids": [],
      "date": 1663844458,
      "default_payment_method": null,
      "default_source": null,
      "default_tax_rates": [],
      "description": null,
      "discount": null,
      "discounts": [],
      "due_date": null,
      "ending_balance": 0,
      "finalized_at": 1663844458,
      "footer": null,
      "forgiven": false,
      "from_invoice": null,
      "hosted_invoice_url": "https://invoice.stripe.com/i/acct_1mMtCKEf7bN****IJNR2/test_YWNjdF8xbU10Q0tF****TmJ0MkJJSk5SMixfTVRramExZWhaRkdDdlZnQzZ2WHVCM1Rja2pCb2s3Myw1NDM5ODkwNw0200eHBEg0mo?s=ap",
      "invoice_pdf": "https://pay.stripe.com/invoice/acct_1mMtCKEf7bNb****JNR2/test_YWNjdF8xbU10Q0tF*****mJ0MkJJSk5SMixfTVRramExZWhaRkdDdlZnQzZ2WHVCM1Rja2pCb2s3Myw1NDM5ODkwNw0200eHBEg0mo/pdf?s=ap",
      "last_finalization_error": null,
      "latest_revision": null,
      "lines": {
        "object": "list",
        "data": [
          {
            "id": "sub_0LknEJCKEf7b****bblGV2Lb",
            "object": "line_item",
            "amount": 3700,
            "amount_excluding_tax": 3700,
            "currency": "usd",
            "description": null,
            "discount_amounts": [],
            "discountable": true,
            "discounts": [],
            "livemode": false,
            "metadata": {},
            "period": {
              "end": 1666436458,
              "start": 1663844458
            },
            "plan": {
              "id": "plan_MTjYr****iEqvG",
              "object": "plan",
              "active": true,
              "aggregate_usage": null,
              "amount": 3700,
              "amount_decimal": "3700",
              "billing_scheme": "per_unit",
              "created": 1663840359,
              "currency": "usd",
              "interval": "month",
              "interval_count": 1,
              "livemode": false,
              "metadata": {},
              "name": "PrimaJust Basic - Normal (normal)",
              "nickname": null,
              "product": "prod_MTjYz****eFSm",
              "statement_descriptor": null,
              "tiers": null,
              "tiers_mode": null,
              "transform_usage": null,
              "trial_period_days": null,
              "usage_type": "licensed"
            },
            "price": {
              "id": "plan_MTjYri****EqvG",
              "object": "price",
              "active": true,
              "billing_scheme": "per_unit",
              "created": 1663840359,
              "currency": "usd",
              "custom_unit_amount": null,
              "livemode": false,
              "lookup_key": null,
              "metadata": {},
              "nickname": null,
              "product": "prod_MTjYz****eFSm",
              "recurring": {
                "aggregate_usage": null,
                "interval": "month",
                "interval_count": 1,
                "trial_period_days": null,
                "usage_type": "licensed"
              },
              "tax_behavior": "unspecified",
              "tiers_mode": null,
              "transform_quantity": null,
              "type": "recurring",
              "unit_amount": 3700,
              "unit_amount_decimal": "3700"
            },
            "proration": false,
            "proration_details": {
              "credited_items": null
            },
            "quantity": 1,
            "subscription": null,
            "subscription_item": "si_MTk****XN365QO",
            "tax_amounts": [],
            "tax_rates": [],
            "type": "subscription",
            "unique_id": "il_0Lkn9KCKEf7****3shtd1N3",
            "unique_line_item_id": "sli_00e967CKEf7****85391f22",
            "unit_amount_excluding_tax": "3700"
          }
        ],
        "has_more": false,
        "total_count": 1,
        "url": "/v1/invoices/in_0LknEJCKEf7b****uRU4Rxf/lines"
      },
      "livemode": false,
      "metadata": {},
      "next_payment_attempt": null,
      "number": "77E****23A-0001",
      "on_behalf_of": null,
      "paid": true,
      "paid_out_of_band": false,
      "payment": "ch_2LknEJCKEf7bN****V5n5Yvt",
      "payment_intent": "pi_2LknEJCKEf7bN****1cYRKSxK",
      "payment_settings": {
        "default_mandate": null,
        "payment_method_options": null,
        "payment_method_types": null
      },
      "period_end": 1663844458,
      "period_start": 1663844458,
      "post_payment_credit_notes_amount": 0,
      "pre_payment_credit_notes_amount": 0,
      "quote": null,
      "receipt_number": null,
      "rendering_options": null,
      "starting_balance": 0,
      "statement_descriptor": null,
      "status": "paid",
      "status_transitions": {
        "finalized_at": 1663844458,
        "marked_uncollectible_at": null,
        "paid_at": 1663844458,
        "voided_at": null
      },
      "subscription": "sub_0LknEJCKEf****t2bblGV2Lb",
      "subtotal": 3700,
      "subtotal_excluding_tax": 3700,
      "tax": null,
      "tax_percent": null,
      "test_clock": "clock_0LknBQCKEf****t24PjP6QSa",
      "total": 3700,
      "total_discount_amounts": [],
      "total_excluding_tax": 3700,
      "total_tax_amounts": [],
      "transfer_data": null,
      "webhooks_delivered_at": 1663844458
    }
  ],
  "has_more": false,
  "url": "/v1/invoices"
}

I tried this: $count = substr_count($result, $invoice);

where $result is the whole json and $invoice = '"object": "invoice"'.

This does work. It returns 2, which is correct. However, maybe there is a better solution? A more reliable solution?

CodePudding user response:

Here you go

$arr = json_encode($jsonResponse /*from stripe*/, true);
$invoiceCount = count($arr["data"]);

CodePudding user response:

You can use regular expresions like

preg_match_all($string, 'object": "invoice', $matches);
$count = count($matches);
  • Related