I'm trying to make JSON to send it to webservice. Final json should looks like:
{
"name": "Pravidlo",
"partQualities": [
"A",
"O",
"N"
],
"residualValueMax": 100,
"residualValueMin": 0,
"selectionStrategy": "MIN_PRICE",
"suppliers": [
864,902,903,907,910,911,913,914,915,916,917,957
],
"vehicleAgeMax": 100,
"vehicleAgeMin": 0
}
What I did try:
$data = array (
"name" => "Pravidlo",
"partQualities" => array(
'A', 'O', 'N'
),
"residualValueMax" = "100",
"residualValueMin" = "0",
"selectionStrategy" = "MIN_PRICE",
"suppliers" = array(
864,902,903,907,910,911,913,914,915,916,917,957
),
"vehicleAgeMax" = "100",
"vehicleAgeMin" = "0"
);
// json encode data
$data_string = json_encode($data);
How Ever I'm getting error with "unexpect" = between residualValueMax and 100.
Can someone please advise me how to create JSON like that ?
Thanks
You need to replace the = with => in the array declaration.
Use => and not = for an array.
Related
im currently trying to update an array with values from another one.
Basically there is a form where you can update data for an object, the form sends a json array like so:
{
"name": "Test2",
"address": "Adresas 2",
"object_id": "44",
"job_id": [
"31",
"33"
],
"amount": [
"500",
"500"
]
}
My goal is to update another array that is being fetched from the database with values of job_idd and amount.
The array from database looks like so:
{
"jobs": [
{
"id": "31",
"amount": "500",
"have": 250
},
{
"id": "33",
"amount": "500",
"have": 0
}
]
}
I need to update the second array values "amount" with the posted values from the first array "amount", but so that the second array still has the original "have" values
I tried using nested foreach method:
$object_id = $_POST['object_id'];
$data = json_encode($_POST);
$json = json_decode($data, true);
$i = 0;
foreach($json['job_id'] as $item) {
$job_id = $item;
$query33 = "SELECT * FROM `objektai` WHERE id='$object_id'";
$result33 = mysqli_query($conn, $query33) or die(mysqli_error($conn));
while($row2 = mysqli_fetch_array($result33)){
$job_info = $row2['info'];
}
$json_22 = json_decode($job_info, true);
foreach ($json_22['jobs'] as $key2 => $entry2) {
$have = $json_22['jobs'][$key2]['have'];
}
$result["jobs"][] = array(
'id' => $job_id,
'kiekis' => $json['amount'][$i],
'turima' => $have,
);
$i++;
}
Usinng the example above the foreach prints the values 2 times and my updated json "have"
has a value of 0, the "amount" entries are updated correctly
Thanks in advance for you help!
UPDATE
adding var_export($_POST):
array ( 'name' => 'Test2',
'address' => 'Adresas 2',
'object_id' => '44',
'job_idd' => array (
0 => '31',
1 => '33',
),
'darbo_kiekis' => array (
0 => '500',
1 => '500',
),
)
When you're looping through the array from the database, you need to compare the id value with $obj_id.
I've also shown below how to use a prepared statement to prevent SQL injection.
I've removed lots of unnecessary code:
No need to convert $_POST to/from JSON.
Use $i => in the foreach loop to get the array index.
You don't need a while loop when processing the query results if it only returns one row.
You don't need $key2, you can just use $entry2.
$object_id = $_POST['object_id'];
$query33 = "SELECT * FROM `objektai` WHERE id = ?";
$stmt33 = $conn->prepare($query33);
$stmt33->bind_param('i', $job_id);
foreach($_POST['job_id'] as $i => $job_id) {
$stmt33->execute();
$result33 = $stmt33->get_result();
$row2 = $result33->fetch_assoc();
$job_info = $row2['info'];
$json_22 = json_decode($job_info, true);
foreach ($json_22['jobs'] as $entry2) {
if ($entry2['id'] == $job_id) {
$result["jobs"][] = array(
'id' => $job_id,
'kiekis' => $json['amount'][$i],
'turima' => $entry2['have']
);
}
}
}
Hi I am new to php and I faced some problem when I need sum up array in foreach.
I had array like this:
$arrays = [
[
'orderid' => "1",
'price' => "100"
'rate' => "1"
],
[
'orderid' => "2",
'price' => "200"
'rate' => "5"
],
];
What I face when I using foreach, the price * rate will sum continuously but not sum up separately.
$bonus = array();
foreach($arrays as $data){
$bonus = $data['originalPrice'] * $data['rate'];
}
I also tried using array_map() but also cannot get my answer;
WHat I need about :
$array = [
[
'total' => 100;
],
[
'total' => 1000;
]
]
Any idea for help?
UPDATED: ALL THE ANSWER ARE CORRECTED, is the api data give me wrong info lol.
foreach($arrays as $data){
$bonus[]['total'] = $data['price'] * $data['rate'];
}
print_r($bonus);
You are using price so use that property and you need to push the value in the result array. Thus, you need to do:
<?php
$arrays=array(
array(
'orderid' => "1",
'price' => "100",
'rate' => "1"
),
array(
'orderid' => "2",
'price' => "200",
'rate' => "5"
)
);
$bonus = array();
foreach($arrays as $data){
array_push($bonus,$data['price'] * $data['rate']);
}
print_r($bonus);
?>
You can test this code at http://www.writephponline.com/
Foreach is fine, but you need to add to the bonus array rather than override with the result:
$bonus = array();
foreach($arrays as $data){
$bonus[] = array('total' => $data['originalPrice'] * $data['rate']);
}
This is adding arrays to the bonus array.
foreach ($ordersList as $object) {
$entityid = $object->entity_id; //how to give this $entityid with in json
$json='{
"orderNo":$entityid, //here i want to assign the value of $entityid
"customerCode": $customerid,
"dateOrdered": "08-07-2015",
"warehouseId" : ,
"orderLineList":
[
"productId": 1000002,
"qty": 6,
"price": 10
]
}';
}
$data = json_decode($json);
$data_string= json_encode($data);
Don't write JSON strings by hand.
$data = [
"orderNo" => $entityid, //here i want to assign the value of $entityid
"customerCode" => $customerid,
"dateOrdered" => "08-07-2015",
"warehouseId" => null ,
"orderLineList" => [
"productId": 1000002,
"qty": 6,
"price": 10,
],
];
$json = json_encode($data);
json_decode() would give an error for this:
{"orderLineList": [ "productId": 1000002 ]}
Try this code:
foreach ($ordersList as $object) {
//Start with a PHP array
//Don't mess with concatenation, you will get tangled with opening & closing quotes.
//If your information comes in a json format. Use json_decode() to convert it into a PHP array.
//$dateOrder,$warehouseId,$object->customer_id are fictious variables. Replace them with real values.
$orderArray[] = [
'orderNo' => $object->entity_id,
'customerCode' => $object->customer_id,
'dateOrdered' => $dateOrdered,
'warehouseId' => $warehouseId,
'orderLineList' => [
'productId': 1000002,
'qty': 6,
'price': 10
]
];
}
$data_string = json_encode($orderArray);
How would I structure $array so that when I pass it to json_encode
$output = json_encode($array);
the output would be:
$output = [
{apples:"33" ,oranges:"22"},
{apples:"44" ,oranges:"11"},
{apples:"55" ,oranges:"66"},
]
Are there any options I need to use to get the output I need? Or is it all about how I structure my PHP array?
This should work for you:
[] = array
{} = object
key:value = key : value
<?php
$array = [
(object)["apples" => "33", "oranges" => "22"],
(object)["apples" => "44", "oranges" => "11"],
(object)["apples" => "55", "oranges" => "66"],
];
echo $output = json_encode($array);
?>
Output:
[
{
"apples": "33",
"oranges": "22"
},
{
"apples": "44",
"oranges": "11"
},
{
"apples": "55",
"oranges": "66"
}
]
You will just need to pass an array of associative arrays to json_encode
$array = array (
array(
'apples'=>'33',
'oranges'=>'22'
),
array(
'apples'=>'44',
'oranges'=>'11'
),
array(
'apples'=>'55',
'oranges'=>'66'
)
);
you can pass with an array of associative arrays in json_encode($var).
$array = array (
array(
'johan'=>'male',
'age'=>'22'
),
array(
'lucy'=>'female',
'age'=>'24'
),
array(
'donald'=>'male',
'age'=>'28'
)
);
I want to create a array for the following json code.
{
"homeMobileCountryCode": 310,
"homeMobileNetworkCode": 260,
"radioType": "gsm",
"carrier": "T-Mobile",
"cellTowers": [
{
"cellId": 39627456,
"locationAreaCode": 40495,
"mobileCountryCode": 310,
"mobileNetworkCode": 260,
"age": 0,
"signalStrength": -95
}
],
"wifiAccessPoints": [
{
"macAddress": "01:23:45:67:89:AB",
"signalStrength": 8,
"age": 0,
"signalToNoiseRatio": -65,
"channel": 8
},
{
"macAddress": "01:23:45:67:89:AC",
"signalStrength": 4,
"age": 0
}
]
}
I have tried with the following but it is showing parsing error in google maps geomatic api
$a = array("homeMobileCountryCode" => 310,
"homeMobileNetworkCode" => 260,
"radioType" => "gsm",
"carrier" => "T-Mobile");
$jsonVal = json_encode($a);
can anyone help me?
PHP's json_encode does not wrap integers with double quotes, which is invalid json. Try this:
$a = array("homeMobileCountryCode" => "310",
"homeMobileNetworkCode" => "260",
"radioType" => "gsm",
"carrier" => "T-Mobile");
$jsonVal = json_encode($a);
From json to Array:
$array = json_decode(/* json text /*);
From Array to Json
$json = json_encode(/* array Object */);
explanations here but you can skip to clean final code further down.
$cellTower1 = array( "cellId"=> "39627456",
"locationAreaCode"=> "40495",
"mobileCountryCode"=> "310",
"mobileNetworkCode"=> "260",
"age"=> "0",
"signalStrength"=> "-95" );
$cellTower2 = array( "cellId"=> "2222222",
"locationAreaCode"=> "22222",
"mobileCountryCode"=> "222",
"mobileNetworkCode"=> "222",
"age"=> "22",
"signalStrength"=> "-22" );
Then combine all cell towers
$allCellTowers[] = $cellTower1;
$allCellTowers[] = $cellTower2;
//etc... or could be in a loop
Now for MAC addresses and wifiAccessPoints.
$macAddress1 = array (
"macAddress"=> "01:23:45:67:89:AB",
"signalStrength" => "8",
"age" => "0",
"signalToNoiseRatio" => "-65",
"channel" => "8"
);
$macAddress2 = array (
"macAddress" => "01:23:45:67:89:AC",
"signalStrength" => "4",
"age" => "0"
);
$macAddress3 = etc...
just as for cellTower1, cellTower2 the macaddresses 1 & 2 above can be populated with a loop.
Adding them to wifiAccessPoints also can be done in a loop but it done manually below just so you understand.
$wifiAccessPoints[] = $macAddress1;
$wifiAccessPoints[] = $macAddress2;
finally the other elements all go in the resulting array to encode
$myarray = array( "homeMobileCountryCode"=> "310",
"homeMobileNetworkCode"=> "260",
"radioType"=> "gsm",
"carrier"=> "T-Mobile",
"cellTowers"=>$allCellTowers,
"wifiAccessPoints" => $wifiAccessPoints
);
$json = json_encode($myarray);
IN CLEAN CODE IT IS
$cellTower1 = array( "cellId"=> "39627456",
"locationAreaCode"=> "40495",
"mobileCountryCode"=> "310",
"mobileNetworkCode"=> "260",
"age"=> "0",
"signalStrength"=> "-95" );
$allCellTowers[] = $cellTower1;
$macAddress1 = array (
"macAddress"=> "01:23:45:67:89:AB",
"signalStrength" => "8",
"age" => "0",
"signalToNoiseRatio" => "-65",
"channel" => "8"
);
$macAddress2 = array (
"macAddress" => "01:23:45:67:89:AC",
"signalStrength" => "4",
"age" => "0"
);
$wifiAccessPoints[] = $macAddress1;
$wifiAccessPoints[] = $macAddress2;
$myarray = array( "homeMobileCountryCode"=> "310",
"homeMobileNetworkCode"=> "260",
"radioType"=> "gsm",
"carrier"=> "T-Mobile",
"cellTowers"=>$allCellTowers,
"wifiAccessPoints" => $wifiAccessPoints
);
//note that you have your first key missing though in your example
$json = json_encode($myarray);