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']
);
}
}
}
Related
I am new to API I used Codeigniter to create an APi from a MySql Databse Products which have
the field : Amount , quantity, customerName, CustomerPhone, CustomerAddress
the rsult looks:
```[
{
"Id": "1",
"Amount": "21542",
"quantity": "52",
"customerName": "John",
"CustomerPhone": "254215",
"CustomerAddress": "road tvz120",
},```
but i want it to look this way:
```[
{
"Id": "1",
"Amount": "21542",
"quantity": "52",
"customerInfo":{
"customerName": "John",
"CustomerPhone": "254215",
"CustomerAddress": "rue tvz120"},
},```
I mean to group the 3 field concernign customers with the name customer info
my php code is
```public function index_get($id = 0)
{
if(!empty($id)){
$data = $this->db->get_where("Products", ['Id' => $id])->row_array();
}else{
$data = $this->db->get("Products")->result();
}
$this->response($data, REST_Controller::HTTP_OK);
}```
Your Products format is based on database, therefore if you want to change the result format, you have to construct it manually. You need to loop the result before returning the data.
if(!empty($id)){
$data = $this->db->get_where("Products", ['Id' => $id])->row_array();
}else{
$data = $this->db->get("Products")->result();
$newdata = array();
foreach($data as $row)
{
$newdata[] = array(
"Id" => $row->id,
"Amount" => $row->amount,
"quantity" => $row->quantity,
"customerInfo" => array(
"customerName" => $row->customerName,
"CustomerPhone" => $row->CustomerPhone,
"CustomerAddress" => $row->CustomerAddress,
)
);
}
$data = $newdata;
}
$this->response($data, REST_Controller::HTTP_OK);
You cannot perform this via query, you'll have to loop through the result and change it to the desired format, like so -
if(!empty($id)){
$result = $this->db->get_where("Products", ['Id' => $id])->result();
// I'll advise to use result() here instead of row_array() so that you don't face any issue when there's only one row.
}else{
$result = $this->db->get("Products")->result();
}
foreach($result as $res){
$new_result[] = array(
"Id" => $res->Id,
"Amount" => $res->Amount,
"quantity" => $res->quantity,
"customerInfo" => array(
"customerName" => $res->customerName,
"CustomerPhone" => $res->CustomerPhone,
"CustomerAddress" => $res->CustomerAddress
)
);
}
$this->response($new_result, REST_Controller::HTTP_OK); // send newly created array instead
See if this helps you.
How to insert a foreach loop inside a multidimensional array ?
I have a multidimensional array that I use to connect my website to Mailchimp. I have to check with a foreach loop the number of products that the user buys, and add these insiede a array call "lines".
This is at moment my json code, that after I will send to Mailchimp:
$json_data = '{
"id": "2'. $order->id .'",
"customer": {
"id": "71",
"email_address": "'.$order->email.'",
"opt_in_status": true,
"company": "'.$order->company_name.'",
"first_name": "'.$order->pad_firstname.'",
"last_name": "'.$order->pad_lastname.'",
"orders_count": 1,
"total_spent": 86
},
"checkout_url": "https://www.mywebsite.it/en/checkout/confirmation/",
"currency_code": "EUR",
"order_total": 86,
"lines"[{
'.$line_result.'
}]
}';
The $line_result is where I try to add the array of the products.
I know is wrong.
all the array inside the "lines" need be like this:
"lines":[
{
data product 1 ...
},
{
data product 2 ...
}
]
This is my foreach:
foreach ($order->pad_products as $product) {
$line_result['line'] = array(
"id" => "$order->id",
"product_id" => "$product->pad_product_id",
"product_title" => "$product->title",
"product_variant_id" => "$product->id",
"product_variant_title" => "$product->title",
"quantity" => "$product->pad_quantity",
"price" => "$product->prezzo",
);
};
what is the correct way to insert this data and create a multidimensional array like the one I need?
Thank you.
You just need to store all $line_result in global variable, and then, bind it to your json model :
$results = [];
foreach ($order->pad_products as $product) {
$results[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
};
$data = json_decode($json_data, true);
$data['lines'] = $results;
$json = json_encode($data);
EDIT : Script array to json
$lines = [];
foreach ($order->pad_products as $product) {
$lines[] = array(
"id" => $order->id,
"product_id" => $product->pad_product_id,
"product_title" => $product->title,
"product_variant_id" => $product->id,
"product_variant_title" => $product->title,
"quantity" => $product->pad_quantity,
"price" => $product->prezzo,
);
}
$data = [
'id' => '2'.$order->id,
'customer' => [
'id' => '71',
'email_address' => $order->email,
'opt_in_status' => true,
'company' => $order->company_name,
'first_name' => $order->pad_firstname,
'last_name' => $order->pad_lastname,
'orders_count' => 1,
'total_spent' => 86
],
'checkout_url' => 'https://www.mywebsite.it/en/checkout/confirmation',
'currency_code' => 'EUR',
'order_total' => 86,
'lines' => $lines
];
$jsonData = json_encode($data, JSON_UNESCAPED_UNICODE);
I want say thank you to #adrianRosi for the help and the input he gives me.
In the end I find my solution, that it's json_encode the array before add into $data in json format.
in this way:
$product_list = [];
foreach ($order->pad_products as $product) {
$product_list[] = array(
"id" => "$id",
"..." => "...",
);
};
$data_products['lines'] = $product_list;
$json_products = json_encode($data_products);
$json_products_edit = substr($json_products, 1, -1); // to delete the {}
$prezzo_totale = $order->pad_price_total;
$json_data = '{
...
...
'.$json_products_edit.'
}';
I am trying to compare two arrays and update specific array values based on conditions.
Getting attendance array of absent students:
$array1 =
array(
array("student_id" => "2",
"date" => "2016-04-24"),
array("student_id" => "6",
"date" => "2016-04-24"));
$attendance = json_decode(json_encode($array1));
Getting student list array of all students:
$array2 =
array(
array("student_id" => "1",
"Reason" => "",
"date" => "2016-04-24"),
array("student_id" => "2",
"Reason" => "",
"date" => "2016-04-24"),
array("student_id" => "3",
"Reason" => "",
"date" => "2016-04-24"),
array("student_id" => "6",
"Reason" => "1",
"date" => "2016-04-24"));
$students = json_decode(json_encode($array2));
Taking out only student IDs of absent students:
foreach($attendance as $att)
{ $atts[] = $att->student_id;}
Here I am trying to find out if any of the students ID in student array matches with ID in absent array. If ID is present then I will update the Reason as "1". Else will make the reason as 0
for ($i = 1; $i <= count($students); $i++) {
if(in_array($atts[$i],$students))
{
$students->Reason='1';
}
else
{
$students->Reason='0';
}
}
echo '<pre>',print_r($students,1),'</pre>';
Here I am unable to update student array with "reason" values.
If you just want to compare student_id from array1 with student_id from array2, and set Reason in array2 if they correspond to each other, use this :
foreach ($array1 as $key1 => $value1) {
foreach ($array2 as $key2 => $value2) {
if ($value1['student_id'] == $value2['student_id']) {
$array2[$key2]['Reason'] = 1;
} else if ($array2[$key2]['Reason'] != 1) {
$array2[$key2]['Reason'] = 0;
}
}
}
I have two arrays (this is an JSON array from PHP)
one
"result1": [
{
"driverId": "3",
"latitude": "23.752182",
"longitude": "90.377730",
"distance": "0.00011211999971692422",
"EstTime": 137
},
{
"driverId": "4",
"latitude": "23.75182",
"longitude": "90.3730",
"distance": "0.000171692422",
"EstTime": 111
}
]
Two
"result2": [
{
"driverId": "3"
}
]
I want to compare these arrays. if any result1 item driverID matches any item of result2 then skip that item from result1
You can do this in two stages.
First gather the driverIds to exclude using array_map
$exclude = array_map(
function($v) {
return $v['driverId'];
},
$json['result2']
);
Then use array_filter to filter out those elements you do not want:
$result = array_filter(
$json['result1'],
function($a) use ($exclude) {
return !in_array($a['driverId'], $exclude);
}
);
I have tested this with the following code. If you have separate arrays, just supply them independently above instead of using $json['result1'].
$a = <<<JSON
{
"result1": [
{
"driverId": "3",
"latitude": "23.752182",
"longitude": "90.377730",
"distance": "0.00011211999971692422",
"EstTime": 137
},
{
"driverId": "4",
"latitude": "23.75182",
"longitude": "90.3730",
"distance": "0.000171692422",
"EstTime": 111
}
],
"result2": [
{
"driverId": "3"
}
]
}
JSON;
$json = json_decode($a, true);
Try the following. In this answer I am assuming that you have already applied json_decode() and extracted $result1 and $result2 into PHP arrays.
Further to your last comment, code edited to work in version 5.2
<?php
// associative array of result1
$result1 = array(
array(
'driverId' => '3',
'latitude' => '23.752182',
'longitude' => '90.377730',
'distance' => '0.00011211999971692422',
'EstTime' => 137
),
array(
'driverId' => '4',
'latitude' => '23.75182',
'longitude' => '90.3730',
'distance' => '0.000171692422',
'EstTime' => 111
)
);
// associative array of result2
$result2 = array(
array(
'driverId' => '3'
)
);
// first, let's get a list of ids that we want to exclude
// run array map over the result2 and return the ids - this
// creates an array of "exclusion" ids. Note you could use
// foreach here also.
function pluckResultIds($result) {
return $result['driverId'];
}
$excludeIds = array_map('pluckResultIds', $result2);
var_dump($excludeIds); // result: array(3)
// next let's use array_filter to run over result1. for each
// entry in result1 - we check if the current driverId is in
// the exclusion array - if it is *not* we return the current
// this creates a new array $filtered containing only the
// filtered elements that do not match
$filtered = array();
foreach ($result1 as $result) {
$id = $result['driverId'];
if (!in_array($id, $excludeIds)) {
$filtered[] = $result;
}
};
var_dump($filtered);
Yields:
array (size=1)
1 =>
array (size=5)
'driverId' => string '4' (length=1)
'latitude' => string '23.75182' (length=8)
'longitude' => string '90.3730' (length=7)
'distance' => string '0.000171692422' (length=14)
'EstTime' => int 111
Hope this helps! :)
I've seen lots of similar question on here, but I haven't been able to get my desired output. Could someone please help me out? How can generate the following JSON structure? My query is fine, I just can't figure out how to loop through and get this. Thanks
DESIRED OUTPUT
{
"players": [
{
"id": 271,
"fname": "Carlos",
"lname": "Beltran",
"position": "OF",
"stats": [
{
"year": "2010",
"hr": 32,
"rbi": 99,
"team": "NYM"
},
{
"year": "2011",
"hr": 35,
"rbi": 100,
"team": "STL"
},
{
............
}
]
},
{
........
}
]
}
CURRENT OUTPUT
{"0":{"cbs_id":"18817","fname":"Carlos","lname":"Beltran"},"stats":[{"year":"2007","hr":"33","rbi":"112"}]}
{"0":{"cbs_id":"174661","fname":"Willie","lname":"Bloomquist"},"stats":[{"year":"2007","hr":"2","rbi":"13"}]}
{"0":{"cbs_id":"1208693","fname":"Brennan","lname":"Boesch"},"stats":[{"year":"2010","hr":"14","rbi":"67"}]}
Which is generated with: (I know I'm way off)
if ($result = mysqli_query($link, $sql)) {
$player = array();
while ($row = $result->fetch_assoc())
{
$player[] = array (
'cbs_id' => $row['cbs_id'],
'fname' => $row['fname'],
'lname' => $row['lname']
);
$player['stats'][] = array(
'year' => $row['year'],
'hr' => $row['hr'],
'rbi' => $row['rbi']
);
}
$json = json_encode($player);
echo "<pre>$json</pre>";
mysqli_free_result($result);
}
}
NOTE: Each player can have more than one "stats" record (year, hr, rbi, etc)
This may give what you want:
$players = array();
while ($row = $result->fetch_assoc())
{
$id = (int)$row['cbs_id'];
if ( ! isset($players[$id]))
{
// New player, add to $players array.
// For the moment index players by ID so stats can be easily added
// to an existing player. Without indexing (using $players[] = ...),
// the same player would be added for each stats record related to
// him.
$players[$id] = array(
'id' => $id,
'fname' => $row['fname'],
'lname' => $row['lname'],
'stats' => array()
);
}
// Add the stats
$players[$id]['stats'][] = array(
'year' => (int)$row['year'],
'hr' => (int)$row['hr'],
'rbi' => (int)$row['rbi']
);
}
// Players are indexed by their ID in $players but need to be contained in
// a JSON array, so use array_values() to remove indices, e.g. convert
//
// array(
// 271 => array('id' => 271, ...),
// ...
// )
//
// to
//
// array(
// array('id' => 271, ...),
// ...
// )
//
$data = array('players' => array_values($players));
$json = json_encode($data);
Eventually you might leave out the integer casts and let PHP automatically convert stringified numeric data (that's the default behaviour with MySQL query results) back to PHP numbers by using the MYSQLI_OPT_INT_AND_FLOAT_NATIVE mysqli connection option as described in example #5 of this page. Note that it requires the mysqlnd library to be used by PHP (you can check that with phpinfo).
You need an associative array. Something like this should get you started:
$data = array(
'players' => array(
array(
'id' => 271,
'fname': 'Carlos',
'lname': 'Beltran',
'position': 'OF',
'stats' => array(
array(
'year' => 2010,
'hr': 32,
'rbi': 99,
'team': 'NYM'
),
...
)
),
...
)
);
To encode it into json, use json_encode:
$json = json_encode($data);