How do I strip unnecessary [] ?
In comp.lang.php The Doctor <doc...@doctor.nl2k.ab.ca> wrote:procircle.png","description":"Protecting Pollinators","product_code":"PP-1294","unit_cost":60,"quantity":"1"}},{"items":{"url":"https:\/\/www.pdsolutions.ca\/images\/procircle.png","description":"Agricultural Health Study","product_code":"AHS-1298","unit_
$contact_details=[];[...]
$contact_details[] = array([...]
"contact_details"=>array(
'first_name' =>$_POST['bill_first_name'],
'last_name' => $_POST['bill_last_name'],
'email' => $_POST['email'],
'phone' => $_POST['bill_phone'],
)
);
$myObj = array_merge($storevalues,$cartarray,$contact_details,$billing_details);
$myJSON = json_encode($myObj);
Here is and example of what is generated:
[{"username":"demouser","password":"password","store_id":"store3","checkout_id":"chkt23NGFtore3","api_token":"yesguy","txn_total":"189.00","environment":"qa","action":"preload"},{"cart":[[{"items":{"url":"https:\/\/www.pdsolutions.ca\/images\/
And here is what is being looked for
{
"store_id":"moneris",
[...]
}
How do I strip unnecessary [] ?First of all, you should strip unnecessary information from your
postings - in your case the content of $myObj and the output are the
only necessary information.
#v+
$a = array();
$b = array();
$a[] = ['contact_details' => ['y' => 'z']];
$b[] = ['billing_details' => ['y' => 'z']];
$c = array_merge($a, $b);
var_dump(json_encode($c));
#v-
string(59) "[{"contact_details":{"y":"z"}},{"billing_details":{"y":"z"}}]"
#v+
$a = ['contact_details' => ['y' => 'z']];
$b = ['billing_details' => ['y' => 'z']];
$c = array_merge($a, $b);
var_dump(json_encode($c));
#v-
string(55) "{"contact_details":{"y":"z"},"billing_details":{"y":"z"}}"
So there is no need to use reduce() or anything else. You are simply
using one (non-associative) level of arrays too much. This would be
easier to debug if you add a print_r($myObj); to your debugging
output.
Personally I'd prefer another version without the irritating
array_merge for better readability, but this is just a matter of
taste producing the same array and the same output:
#v+
$a = ['y' => 'z'];
$b = ['y' => 'z'];
$c = ['contact_details' => $a, 'billing_details' => $b]; var_dump(json_encode($c));
#v-
Bye,
Stefan
--
http://kontaktinser.at/ - die kostenlose Kontaktboerse fuer Oesterreich Offizieller Erstbesucher(TM) von mmeike
Stefan: die süße Verführung!
(Sloganizer)
On Tue, 10 Jan 2023 01:17:47 -0000 (UTC), The Doctor wrote:
How do I strip unnecessary [] ?I'd use array's `reduce()` for that. e.g.
var resultObj = theArray.reduce((res, obj) => Object.assign(res, obj), {});
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 379 |
Nodes: | 16 (2 / 14) |
Uptime: | 71:40:19 |
Calls: | 8,084 |
Calls today: | 2 |
Files: | 13,069 |
Messages: | 5,849,953 |