PHP Checkboxes in an array - php

When a form gets posted, I get some checkbox values like the below:
Array ( [chk0] => true ,
[chk1] => true,
[chk3] => true,
[chk1002] => on,
[chk1005] => on
)
Using PHP,How can I construct a JSON request like this by using the above variables?
"data":
[
{
"checkboxval": true,
"id": 0
},
{
"checkboxval": true,
"id": 1
},
{
"checkboxval": true,
"id": 3
},
{
"checkboxval": true,
"id": 1002
},
{
"checkboxval": true,
"id": 1005
}
]
Please note that my POST variables can have other form variables too, but all checkbox values will be named with the prefix "chk"

$output = array();
foreach ($input as $k => $v) {
$output[] = array(
'checkboxval' => !!$v,
'id' => preg_replace('!^chk!', '', $k),
);
}
header('Content-Type: application/json');
echo json_encode(array('data' => $output));

foreach ($_POST as $k => $v) {
$output[] = array(
'checkboxval' => ($v=='on'? true : ($v=='off' ? false : !!$v)),
'id' => preg_replace('!^chk!', '', $k),
);
}
header('Content-Type: application/json');
echo json_encode(array('data' => $output));
Credits to cletus who provided the basis for this code.

Have a look at the json_encode() php function. You'll have to massage your array a little to get the exact JSON format you're after.

Heres an example...
$_POST["chk1"] = "Hello";
$_POST["chk2"] = "World";
$jsonArray = array();
foreach($_POST as $key => $val){
if(preg_match("/chk/", $key)){
$jsonArray[$key] = $val;
}
}
$jsonArray = array("Data" => $jsonArray);
$json = json_encode($jsonArray);
echo "<pre>";
echo $json;
echo "</pre>";
Outputs this:
{"Data":{"chk1":"Hello","chk2":"World"}}

I haven't tested this yet, but maybe something like this:
$json = '"data": [';
$first = true;
foreach ($_POST as $k => $v){
if (preg_match('/^chk(\d+)$/', $k, $m)){
if ($first) $first = false; else $json .= ", ";
$json .= sprintf('{ "checkboxval" : %s, "id" : %s }', ($v && $v != "off") ? "true" : "false", $m[1]);
}
}
$json .= ']';

Related

PHP merge array by "depth"? [duplicate]

This question already has answers here:
How to array_merge_recursive() an array?
(2 answers)
Closed 3 months ago.
I have an array like this:
[
{
"function_1": {
"element": {
"error": "0",
"msg": "test"
}
}
},
{
"function_1": {
"element_2": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element_2": {
"error": "0",
"msg": "test"
}
}
}
]
I want output like this:
[
{
"function_1": {
"element": {
"error": "0",
"msg": "test"
},
"element_2": {
"error": "0",
"msg": "test"
}
}
},
{
"function_2": {
"element": {
"error": "0",
"msg": "test"
},
"element_2": {
"error": "0",
"msg": "test"
}
}
}
]
The answers that I found offered to search by name("function_1", "function_2"). But this does not suit me, the function will not always pass an array. I need exactly the "depth" or any other reasonable way.
Thank you!
To achieve your desired result, you could json-decode, recursively merge each individual subarray, then loop over that structure to push each item as a second-level array like this: (Demo)
$array = json_decode($json, true);
$merged = array_merge_recursive(...$array);
$result = [];
foreach ($merged as $key => $data) {
$result[] = [$key => $data];
}
var_export($result);
But I can't imagine getting any benefit from adding unnecessary depth to your result array. I recommend simply json decoding, then calling array_merge_recursive() with the spread operator: (Demo)
var_export(
array_merge_recursive(
...json_decode($json, true)
)
);
Output:
array (
'function_1' =>
array (
'element' =>
array (
'error' => '0',
'msg' => 'test',
),
'element_2' =>
array (
'error' => '0',
'msg' => 'test',
),
),
'function_2' =>
array (
'element' =>
array (
'error' => '0',
'msg' => 'test',
),
'element_2' =>
array (
'error' => '0',
'msg' => 'test',
),
),
)
Your data structure looks weird for the purpose you are trying to achieve I'm bored af tho and created this code for you
function combineElementsPerfunction($functions) {
$result = [];
$uniqueFunctions = [];
foreach ($functions as $function) {
$functionName = array_keys($function)[0];
$uniqueFunctions[] = $functionName;
}
$uniqueFunctions = array_unique($uniqueFunctions);
foreach ($uniqueFunctions as $uniqueFunction) {
$functionObjects = array_filter(
$functions,
function($function) use ($uniqueFunction) {
$functionName = array_keys($function)[0];
return $functionName === $uniqueFunction;
}
);
$elements = [];
foreach ($functionObjects as $functionObject) {
$function = array_shift($functionObject);
$elements = array_merge($elements, $function);
}
$result[] = [
$uniqueFunction => $elements
];
}
return $result;
}
function changeArr($data){
$box = $new = [];
foreach ($data as $v){
$key = array_key_first($v);
$i = count($box);
if(in_array($key, $box)){
$keys = array_flip($box);
$i = $keys[$key];
}else{
$box[] = $key;
}
$new[$i][$key] = isset($new[$i][$key]) ? array_merge($new[$i][$key], $v[$key]) : $v[$key];
}
return $new;
}

Formatting API JSON response using PHP

I have an api and i want to parse data from it using php
That's the response
{
"success": true,
"data": [
{
"medicineId": 12,
"medicineName": "Abacavir"
},
{
"medicineId": 10,
"medicineName": "Alclometasone"
},
{
"medicineId": 15,
"medicineName": " Alectinib"
},
{
],
"message": "Successfully retrieved"
}
I want to list all medicine names
i tried this but it doesn't get the name just the success response
$age = file_get_contents('link');
$array = json_decode($age, true);
foreach($array as $key=>$value)
{
echo $key . "=>" . $value . "<br>";
}
You can easily list all medicine names with their id like this way by looping $array['data'] array. Let's do this way-
<?php
$age = '{"success":true,"data":[{"medicineId":12,"medicineName":"Abacavir"},{"medicineId":10,"medicineName":"Alclometasone"},{"medicineId":15,"medicineName":" Alectinib"}],"message":"Successfully retrieved"}';
$array = json_decode($age, true);
$medicine_names = [];
foreach($array['data'] as $key=>$value)
{
$medicine_names[$value['medicineId']] = $value['medicineName'];
}
print_r($medicine_names);
echo implode(' ', $medicine_names);
?>
Output:
Array (
[12] => Abacavir
[10] => Alclometasone
[15] => Alectinib
)
WORKING DEMO: https://3v4l.org/tBtaW

how to get object value

I have this object in my session
name: "test",
is_feature: "0",
attributes: [
{
'5': "blue"
},
{
'7': "iOS"
}
],
cost: "2000",
I want to use attributes in foreach.some thing like below code:
foreach ($product->attributes as $attribute){
ProductAttributeValue::create([
'attribute_id' => $attribute->key, //like 5,7
'value' => $attribute->value //like blue,iOS
]);
}
Try this loop:
First you convert json to associative arrays like:
$productAttributes = json_decode($product->attributes, true);
and then
foreach ($productAttributes as $attributes) {
foreach ($attributes as $key => $attribute) {
ProductAttributeValue::create([
'attribute_id' => $key, // like 5,7
'value' => $attribute // like blue,iOS
]);
}
}
I hope it would helpful.
You use this:
$str = '{"name": "test", "is_feature": "0", "attributes": [{"5": "blue"},{"7": "iOS"}],"cost": "2000"}';
$arr = json_decode($str, true); // convert the string to associative array
foreach($arr["attributes"] as $attribute) {
$key = key($attribute); // get the first key as "5" of "7"
echo "key: $key and val: " . $attribute[$key]; // access the value as $attribute[$key] will give blue or ios
};
Live example: 3v4l
Reference: key
Here is a solution for you.
$strArr = [
'name'=>"test",
'is_feature'=> "0",
'attributes'=>[[5=> "blue"],[7=> "iOS"]],
'cost'=> "2000"
];
$str = json_encode($strArr);
$arr = (array) json_decode($str);
$att = (array) $arr['attributes'];
foreach($att as $val) {
foreach($val as $key=>$attributes) {
echo "key: ".$key." and val: " . $attributes . PHP_EOL;
}
};
Output:
key: 5 and val: blue
key: 7 and val: iOS
Hope this will help you

Fix PHP condition when decoding JSON

I'm decoding a json file using php.
In foreach statement I check if my cd_driver is in the array coming from the json file content. If it's in the array the script updates its month as expected. If not, the script writes the new driver into the json file.
Everything works fine but it's also executing the else condition after updating its month and adding the same driver to the json file. Why is this happening?
$dados[] = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$dados2 = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$jsonString = file_get_contents('bsaldo.json');
$data = json_decode($jsonString, true);
if($data == ""){
$newString = json_encode($dados);
file_put_contents('bsaldo.json', $newString);
}else {
foreach ($data as $key => $value) {
$mot = $value['cd_driver'];
$array = array();
array_push($array, $mot);
if(in_array($cd_driver, $array)){
$data[$key]['month'] = $cd_month;
$newString = json_encode($data);
file_put_contents('bsaldo.json', $newString);
}else {
array_push($data, $dados2);
$finalString = json_encode($data);
file_put_contents('bsaldo.json', $finalString);
}
}
}
json:
[
{
"cd_driver": "11831",
"Driver": "ADENILSON RODRIGUES DE SOUZA",
"month": "02",
"bsaldo": -903
},
{
"cd_driver": "11835",
"Driver": "EDIVAN DE CASTRO VASSALO",
"month": "01",
"bsaldo": -7670
},
{
"cd_driver": "11831",
"Driver": "ADENILSON RODRIGUES DE SOUZA",
"month": "02",
"bsaldo": -903
},
{
"cd_driver": "11831",
"Driver": "ADENILSON RODRIGUES DE SOUZA",
"month": "02",
"bsaldo": -903
}
]
I had to adapt some things to work with php 5.1.
Your problem is that you are resetting the array on each iteration of the loop. Move it outside of the foreach, like so:
$dados[] = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$dados2 = array('cd_driver' => $cd_driver, 'Driver' => $RSx["ds_name"], 'month' => $cd_month, 'bsaldo' => $saldoToJson);
$jsonString = file_get_contents('bsaldo.json');
$data = json_decode($jsonString, true);
if($data == ""){
$newString = json_encode($dados);
file_put_contents('bsaldo.json', $newString);
}else {
$array = array(); # here it won't be continually reset and can accumulate values as intended.
foreach ($data as $key => $value) {
$mot = $value['cd_driver'];
array_push($array, $mot);
if(in_array($cd_driver, $array)){
$data[$key]['month'] = $cd_month;
$newString = json_encode($data);
file_put_contents('bsaldo.json', $newString);
}else {
array_push($data, $dados2);
$finalString = json_encode($data);
file_put_contents('bsaldo.json', $finalString);
}
}
}

Outputting Array Keys of Multi-Dimensional Array

I'm trying to write a function that takes a multi-dimensional array as input and outputs a multi-line string of keys like the following
['key']['subkey']
['key']['another_subkey']
['key']['another_subkey']['subkey_under_subkey']
['key']['yet_another_subkey']
['another_key']['etc']
Here is my attempt. It has problems when you get to the second level.
function get_array_keys_as_string($array){
$output = "";
foreach($array as $k => $v){
if(is_array($v)){
$string = get_array_keys_as_string($v);
$prepend = "['$k']";
$string = $prepend.str_replace("\n","\n".$prepend, $string);
$output .= $string;
}
else{
$output .= "['$k']\n";
}
}
return $output;
}
I know I need a recursive function, but so far my attempts have come up short.
To get the exact output you asked for use the following:
$arr = array(
"key" => array(
"subkey" => 1,
"another_subkey" => array(
"subkey_under_subkey" => 1
),
"yet_another_subkey" => 1
),
"another_key" => array(
"etc" => 1
)
);
function print_keys_recursive($array, $path = false) {
foreach($array as $key=>$value) {
if(!is_array($value)) {
echo $path."[".$key."]<br/>";
} else {
if($path) {
echo $path."[".$key."]<br/>";
}
print_keys_recursive($value, $path."[".$key."]");
}
}
return;
}
print_keys_recursive($arr);
Output:
[key][subkey]
[key][another_subkey]
[key][another_subkey][subkey_under_subkey]
[key][yet_another_subkey]
[another_key][etc]
Not sure how you want the output since you have not provided an example array, just the result, but here is an example based on the following array,
$array = array(
"key" => array(
"subkey" => 1,
"another_subkey" => array("2", "subkey_under_subkey" => 3),
"yet_another_subkey" => 4
),
"another_key" => array("etc"),
"last_key" => 0
);
Using the following function,
function recursive_keys($arr, $history = NULL)
{
foreach ($arr as $key => $value)
{
if (is_array($value))
recursive_keys($value, $history."['".$key."']");
else
echo $history."['".$key."']\n";
}
}
Output of recursive_keys($array) is,
['key']['subkey']
['key']['another_subkey']['0']
['key']['another_subkey']['subkey_under_subkey']
['key']['yet_another_subkey']
['another_key']['0']
['last_key']
Try this
function arrayMultiKeys($array,$depth = 0){
foreach($array as $k=>$v){
echo "['".$k."']";
if(is_array($v)){
arrayMultiKeys($v,$depth + 1);
}
if($depth == 0 ){
echo "<br>";
}
}
}

Categories