How to get array from php to react axios? - php

Array
(
[0] => Array
(
[images] => projects/0mxlk1duzt/1.png
)
[1] => Array
(
[images] => projects/0mxlk1duzt/2.png
)
[2] => Array
(
[images] => projects/0mxlk1duzt/3.png
)
)
this is array what i have in php file on server, code in php
<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Disposition, Content-Type, Content-Length, Accept-Encoding");
header("Content-type:application/json");
$response = array();
foreach(glob('projects/0mxlk1duzt/*', GLOB_NOSORT) as $image)
{
array_push($response,array(
"images" => $image
));
}
print_r($response);
?>
next i have react app with axios with code:
class Gallery extends React.Component {
state = {
images: []
}
componentDidMount() {
const url = 'http://work.eniso.ru/gallery.php'
axios.get(url).then(response => response.data)
.then((data) => {
this.setState({ images: data })
console.log(this.state.images)
})
}
render(){
return(
<div className='gallery'>
<ul>
{ this.state.images }
</ul>
</div>
)
}
}
Now i can only output this in text format, but I don't understand how to get array and in react i must do array.map to output elements in <li><li>

In PHP I need to do:
echo json_encode($response);
In React I need to array.map:
{ this.state.images.map((response, i) => (
<div key={i}>
<img className='img-prew' src={response.images} />
</div>
))}

Related

How to create nested tag in JSON

I have been fiddling with JSON nested tag, tried the basics now I want to go a little further, but it has been giving a little head ache to me. I have this public function below
public function returnResponse($code, $data){
header("content-type: application/json");
$result = json_encode(['response' => ['status' => $code, "message" => $data]]);
echo $result ; exit;
}
$order= $cust->getDeliveryDetail();
USING print_r($order);
Array
(
[0] => Array
(
[0] => Array
(
[order_id] => 4444
[menu] => two
[order_uniq] => 999oeo4
)
)
[1] => Array
(
[0] => Array
(
[pro_name] => Beans
[pro_sub] => Goods
[pro_type] => Open CA
)
[1] => Array
(
[pro_name] => Rice
[pro_sub] => Fiber
[pro_type] => Diverca
)
)
)
then attaching object with elements and value which references
$result ['order_id'] = $order[0][0]['order_id'];
$result ['menu'] = $order[0][0]['menu'];
$result ['order_uniq'] = $order[0][0]['order_uniq'];
$result ['pro_name'] = $order[0][0]['pro_name'];
$result ['pro_sub'] = $order[0][0]['pro_sub'];
$result ['pro_type'] = $order[0][0]['pro_type'];
$this->returnResponse(SUCCESS_RESPONSE, $result); //THIS IS THE ORIGINAL BEGINNING PUBLIC FUNCTION WE CREATED
to create this JSON nested tag below
{
"response": {
"status": 200,
"message": {
"order_id": "4444",
"menu": "two",
"order_uniq": "999oeo4",
"pro_name": "Beans",
"pro_sub": "Goods",
"pro_type": "Openca",
}
}
}
but I want to create a JSON nested tag like this below
{
"response": {
"status": 200,
"message": {
"order_id": "4444",
"menu": "two",
"order_uniq": "999oeo4",
"items": [
{
"pro_name": "Beans",
"pro_sub": "Goods",
"pro_type": "Openca",
}
{
"pro_name": "Rice",
"pro_sub": "Fiber",
"pro_type": "Diverca",
}
]
},
}
}
If it helps -- maybe not, the right way to do this in the beginning would be to create an OrderItems table/dictionary. Then store items in that table referrencing your Order table with "order_id". That way you could pull order_items as one array object, and convert that to json really simply.
Here since, you are getting "pro_name", "pro_sub" & "pro_type" as items, you would programmatically pull those out and create your own order_items array.
$order= $cust->getDeliveryDetail();
$order_id = $order[0][0]['order_id'];
$order_menu = $order[0][0]['menu'];
$order_uniq = $order[0][0]['order_uniq'];
$items = [];
foreach($order[1] as $order_item) {
$items[] = $order_item;
}
$result = [];
$result["order_id"] = $order_id;
$result["menu"] = $order_menu;
$result["order_uniq"] = $order_uniq;
$result["order_items"] = $items;
$this->returnResponse(SUCCESS_RESPONSE, $result);
Like this?
$result = array(
'order_id' = > $order[0][0]['order_id'],
'menu' => $order[0][0]['menu'],
'order_uniq' => $order[0][0]['order_uniq'],
'pro_name' => $order[0][0]['pro_name'],
'pro_sub' => $order[0][0]['pro_sub'],
'pro_type' => $order[0][0]['pro_type'],
'items' => array()
);
foreach($order[1] as $item) {
array_push(
$result['items'],
array(
'pro_name' => $item['pro_name'],
'pro_sub' => $item['pro_sub'],
'pro_type' => $item['pro_type'],
)
);
}

Retrieve value from SimpleXML object in PHP

$bbb = new BigBlueButton();
$recordingsParams = array(
'meetingId' => '',
);
// Now get recordings info and display it:
$itsAllGood = true;
try {$result = $bbb->getRecordingsWithXmlResponseArray($recordingsParams);}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
$itsAllGood = false;
}
if ($itsAllGood == true) {
if ($result == null) {
echo "Failed to get any response. Maybe we can't contact the BBB server.";
}
else {
if ($result['returncode'] == 'SUCCESS') {
echo "<p>Meeting info was found on the server.</p>";
}
else {
echo "<p>Failed to get meeting info.</p>";
}
print_r($result);
}
}
When I am using Bigbluebutton, I need to retrieve the particular data from these XML format response. I don't know how to retrieve the particular data from these XML format?
Array
(
[returncode] => SimpleXMLElement Object
(
[0] => SUCCESS
)
[0] => Array
(
[meetingId] => SimpleXMLElement Object
(
[0] => newtech
)
)
[1] => Array
(
[meetingId] => SimpleXMLElement Object
(
[0] => menew
)
)
)
I need to display the values of meetingId.
If you'd rather work with arrays you can cast the XML as well. This function returns an array with info on what is going on on your server if called (improvements still very welcome):
function getServerInfo() {
$url="https://you-bbb-server-api-getMeetings-call-url";
$a= (array)new SimpleXMLElement(file_get_contents($url));
if($a["returncode"]=="SUCCESS") {
if($a["meetings"]) {
foreach($a["meetings"] as $meeting) {
$meeting=(array)$meeting;
$data["Meetings"][$meeting["meetingID"]]["Teilnehmer"]=$meeting["participantCount"];
$data["Meetings"][$meeting["meetingID"]]["Name"]=$meeting["meetingName"];
$data["Gesamt"]+=(int)$meeting["participantCount"];
$data["Anzahl"]++;
$data["Meetings"][$meeting["meetingID"]]["Video"]=$meeting["videoCount"];
$data["Meetings"][$meeting["meetingID"]]["Start"]=date('d.m.Y H:i:s',floor($meeting["startTime"]/1000));
if($meeting["attendees"]) foreach($meeting["attendees"] as $att) {
$att=(array)$att;
if($att["role"]=="MODERATOR") $data["Meetings"][$meeting["meetingID"]]["Liste"]["M"]=array($att["fullName"],($att["hasJoinedVoice"]=="true")? 1:0,($att["hasVideo"]=="true")? 1:0);
else $data["Meetings"][$meeting["meetingID"]]["Liste"]["T"][]=array($att["fullName"],($att["hasJoinedVoice"]=="true")? 1:0,($att["hasVideo"]=="true")? 1:0);
}
}
return($data);
} else return(array("Anzahl"=>0,"Gesamt"=>0));
} else return(-1);
}

Foreach array to update table of database use those element of array

How to get the first value of element of array in php.
My story board is like this:
I have an array like this:
(
[0] => Array
(
[ID] => 68
[MATERIAL] => I have
[AC] => Try
)
[1] => Array
(
[ID] => 69
[MATERIAL] => It
[AC] => No Surrender
)
)
I want to update some record on my database like this,
foreach element of array,
UPDATE MY TABEL SET MATERIAL = [MATERIAL], AC = [AC] where id= [id]
this is the model named m_admin :
public function update_eir_to_cost($id, $material, $ac) {
$data = array(
"MATERIAL" => $material,
"AC" => $ac);
$this->db->trans_start();
$this->db->where($id);
$this->db->update('tb_repair_detail', $data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE) {
// generate an error... or use the log_message() function to log your error
echo "Error Updating";
} else {
echo "Alhamdulillah";
}
}
This is the controller :
public function update_json_detail() {
$post_data = $this->input->post("POST_ARRAY");
$execute = array();
foreach ($post_data as $data) {
$execute[] = array(
'ID'=> $data['0'],
'MATERIAL' => $data['7'],
'AC' => $data['8']
);
}
echo "<pre>";
print_r($execute); // return an array like above.
/*forech element
update table using model
*/
}
This will solve your problem:
public function update_json_detail() {
$post_data = $this->input->post("POST_ARRAY");
$execute = array();
foreach ($post_data as $data) {
$execute[] = array(
'ID'=> $data['0'],
'MATERIAL' => $data['7'],
'AC' => $data['8']
);
}
echo "<pre>";
print_r($execute); // return an array like above.
$this->load->model('m_admin');
foreach ($execute as $row) {
$this->m_admin->update_eir_to_cost($row['ID'], $row['MATERIAL'], $row['AC']);
}
}

How to make group (if specific field are same text) in loop?

I tried render data in loop and if extend_tag field have same text group in one container.
I only know hard code like below, loop data base on how many known extend_tag group, but actually the extend_tag numbers is unknown might be tag_ and any digit , any idea how to solve it?
data
[tag] => Array (
[0] => Array (
[id] => 1
[extend_tag] => tag_0
)
[1] => Array (
[id] => 2
[extend_tag] => tag_11
)
[2] => Array (
[id] => 3
[extend_tag] => tag_4
)
)
<ul class="container">
<?php foreach($rows['tag'] as $eachRowsTag) { ?>
<?php if ($eachRowsTag['extend_tag'] == 'tag_0') { ?>
<li>><?php echo $eachRowsTag['id']; ?></li>
<?php } ?>
<?php } ?>
</ul>
<ul class="container">
<?php foreach($rows['tag'] as $eachRowsTag) { ?>
<?php if ($eachRowsTag['extend_tag'] == 'tag_1') { ?>
<li>><?php echo $eachRowsTag['id']; ?></li>
<?php } ?>
<?php } ?>
</ul>
...
Why not group them first, then iterate over the resulting array. Something like the following.
foreach ($tags as $tag) {
$grouped[$tag['extend_tag']][] = $tag;
}
// Now $grouped is something along the lines of:
// [
// 'tag_0' => [
// [ 'id' => 1, 'extend_tag' => 'tag_0'],
// ..
// ],
// ..
// ]
foreach($grouped as $extend_tag => $tags) {
echo "All tags in $extended_tag.";
foreach($tags as $tag) {
echo $tag['id'];
}
}
// For something like:
// All tags in tag_0.
// 1
// 4
// All tags in tag_1.
// ..

Codeigniter REST Upload Multiple Images

I'm absolutely stuck on this... checked all related stackoverflow posts and nothing has helped. Using Phil's REST Server / Client setup in Codeigniter and can insert normal entries but cannot upload multiple images, actually even a single image.
I can't really work out how to debug the REST part, it just returns nothing.
I have this array coming in from the view:
Array
(
[1] => Array
(
[name] => sideshows.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phppYycdA
[error] => 0
[size] => 967656
)
[2] => Array
(
[name] => the-beer-scale.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phpCsiunQ
[error] => 0
[size] => 742219
)
[3] => Array
(
[name] => the-little-lace.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phpXjT7WL
[error] => 0
[size] => 939963
)
[4] => Array
(
[name] => varrstoen-australia.jpg
[type] => image/jpeg
[tmp_name] => /Applications/MAMP/tmp/php/phpcHrJXe
[error] => 0
[size] => 2204400
)
)
I am using this helper method I found to sort out multiple file uploads:
function multifile_array()
{
if(count($_FILES) == 0)
return;
$files = array();
$all_files = $_FILES['files']['name'];
$i = 0;
foreach ($all_files as $filename) {
$files[++$i]['name'] = $filename;
$files[$i]['type'] = current($_FILES['files']['type']);
next($_FILES['files']['type']);
$files[$i]['tmp_name'] = current($_FILES['files']['tmp_name']);
next($_FILES['files']['tmp_name']);
$files[$i]['error'] = current($_FILES['files']['error']);
next($_FILES['files']['error']);
$files[$i]['size'] = current($_FILES['files']['size']);
next($_FILES['files']['size']);
}
$_FILES = $files;
}
This function is being called within the API controller:
public function my_file_upload_post() {
if( ! $this->post('submit')) {
$this->response(NULL, 400);
}
$data = $this->post('data');
multifile_array();
$foldername = './uploads/' . $this->post('property_id');
if(!file_exists($foldername) && !is_dir($foldername)) {
mkdir($foldername, 0750, true);
}
$config['upload_path'] = $foldername;
$config['allowed_types'] = 'gif|jpg|png|doc|docx|pdf|xlsx|xls|txt';
$config['max_size'] = '10240';
$this->load->library('upload', $config);
foreach ($data as $file => $file_data) {
$this->upload->do_upload($file);
//echo '<pre>';
//print_r($this->upload->data());
//echo '</pre>';
}
if ( ! $this->upload->do_upload() ) {
return $this->response(array('error' => strip_tags($this->upload->display_errors())), 404);
} else {
$upload = $this->upload->data();
return $this->response($upload, 200);
}
}
I am happy to share my code, I did manage to get multiple files uploading no worries, but just trying to set it up with the API so I can call it from an external website, internally or an iPhone. Help would be appreciated.
Cheers
Update:
Here is the code from the API Controller:
function upload_post() {
$foldername = './uploads/' . $this->post('property_id');
if(!file_exists($foldername) && !is_dir($foldername)) {
mkdir($foldername, 0750, true);
}
$config['upload_path'] = $foldername;
$config['allowed_types'] = 'gif|jpg|png|doc|docx|pdf|xlsx|xls|txt';
$config['max_size'] = '10240';
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload())
{
//return $this->response(array('error' => strip_tags($this->upload->display_errors())), 404);
return $this->response(array('error' => var_export($this->post('file'), true)), 404);
}
else
{
$data = array('upload_data' => $this->upload->data());
return $this->response(array('error' => $data['upload_data']), 404);
}
return $this->response(array('success' => 'successfully uploaded' ), 200);
}
This works if you go directly to the API from the form, but you need to put in the username and password within the browser. If I run this via the controller then it can't find the images.
This is not exactly what you asked for, but this is what I used to solve this problem. A PHP/jQuery upload widget!
http://blueimp.github.com/jQuery-File-Upload/

Categories