generating multidimensional object with array - javascript

I am generating an object like this:
As you can see education is an array inside an object,
but what I want is for degree_1 and major_1 and their values to be in the same object.
This is how I want it but with education as an array:
One other thing:
When I var_dump it in my php it is just fine with the arrays and everything. But my javascript gets the second image above- object of object when it was just an array..
public function show($id)
{
$tmp = array();
$post = array();
$postInfo = Post::find($id);
$params = DB::select( DB::raw("SELECT param.*, sys_param_values.*,param_value.*,type_post.*,
param.name AS paramName,
doc_param.name AS docParamName
FROM param
LEFT JOIN doc_param ON param.doc_param_id = doc_param.id
LEFT JOIN sys_param_values ON param.id = sys_param_values.param_id
LEFT JOIN param_value ON sys_param_values.value_ref = param_value.id
LEFT JOIN type_post ON sys_param_values.ref_id = type_post.id WHERE type_post.id = ".$id));
$isMultiple = false;
$post['postInfo'] = $postInfo['original'];
foreach($params as $k=>$v) {
$iteration = $v->iteration;
$docParamName = $v->docParamName;
$paramName = $v->paramName;
if($v->value_ref == null) {
$value = $v->value_short;
} else {
$value = $v->value;
}
if($iteration) {
$post[$docParamName][$iteration][$paramName] = $value;
// need to return education as array not as object
// $post[$docParamName][] = array($paramName=>$value) ;
}elseif(!$iteration) {
$post[$docParamName][$paramName] = $value;
}
}
return Response::json($post);
}

Make first element from education to 0, now it is 1, so that's why json_encode is parsing it as an object.

I don't know what you data source looks like, but it looks to me that you're fetching vertical data and them want to display it horizontally. If that is the case your data need to be stored in a way that simply looping is enough, if not some PHP logic will be required.
We can't really help you on that until you show us an example of your table contents.
Cheers

Related

shorter way to collect and send data without a form

I have some (15) input, select, and textarea tags on page - without a form
need to collect their values and insert them into a database
this code works fine, but I hope there is a way to short it
on client side - maybe some kind of serialize
on server side - especially on execute statement - maybe some kind of loop
$('#btn_send').on('click', function(){
let obj = {};
$('input, select, textarea').each(function(){
let a = $(this).attr('name');
obj[a] = $(this).val();
});
let str = JSON.stringify(obj);
$.post('reg.php', {fn: 'btn_send', args: [str]}, function(data){
console.log(data);
});
});
reg.php
function btn_send($str){
global $db;
$obj = json_decode($str);
// here are table columns
$a = "name,birth,gender,city,state,gmail,fb,tw,web,phone,occ,food,note,uname,pass";
$b = ':a' . str_replace(',', ', :a', $a);
$sq = "insert into members ($a) values ($b)";
$st = $db->prepare($sq);
$st->execute([
":aname" => $obj->name,
":agender" => $obj->gender,
//... and so on - 15 items
]);
echo 'success';
}
Based on your code sample, it looks like the elements of your object have the same names as the columns in your table. In that case, you can simplify your code by converting the incoming JSON to an array rather than an object and utilising the fact that PDOStatement::execute allows the array keys to not include the : in the names:
$obj = json_decode($str, true);
// here are table columns
$cols = array_keys($obj);
$a = implode(',', $cols);
$b = ':a' . str_replace(',', ', :a', $a);
$sq = "insert into members ($a) values ($b)";
$st = $db->prepare($sq);
$st->execute($obj);
Should the behaviour of execute change in the future, you can make an array with the keys preceded with : using array_combine and array_map:
array_combine(array_map(function ($k) { return ":$k"; }, $cols), $obj)
You would then pass this array to execute in place of $obj.
Something I made not sure if it even compiles, just was bored this is how I would do the 15 items or so part.
function btn_send($str){
global $db;
$obj = json_decode($str);
// here are table columns
$a = "name,birth,gender,city,state,gmail,fb,tw,web,phone,occ,food,note,uname,pass";
$b = ':a' . str_replace(',', ', :a', $a);
$sq = "insert into members ($a) values ($b)";
$st = $db->prepare($sq);
$sqlArray = array();
foreach($obj as $key => $value) {
$sqlArray[]= array(":a".$key => $value);
}
$st->execute($sqlArray);
echo 'success';
}
Edit: I looked at Nick's answer it seems you don't even need to do all the hard stuff I did, you can just pass $obj wow they made it so easy now

SQLSTATE[01000]: Warning: 1265 Data truncated for column 'id_paket' at row 1

SQLSTATE[01000]: Warning: 1265 Data truncated for column 'id_paket' at
row 1 (SQL: insert into tbl_pesanan (id_paket, kode_bmn,
kode_unit, jenis_barang, kuantitas, satuan_ukuran,
status_pesanan) values (18,18, 1010101002,1010101002, 1001,1001,
ASus,ASus, 6,6, UNit,UNit, 1))
what happened, can you help me?
public function store_pesanan(request $request,$id){
if(!Session::get('login')){
return redirect('/login')->with('alert','Kamu harus login dulu');
}
else{
DB::table('tbl_paket')
->where('id_paket',$id)
->update(['status_paket' => $request->status_paket]);
$data = new ModelPesanan();
$data->id_paket = implode(',', $request->input('id_paket'));
$data->kode_bmn = implode(',', $request->input('kode_bmn'));
$data->kode_unit = implode(',', $request->input('kode_unit'));
$data->jenis_barang = implode(',', $request->input('jenis_barang'));
$data->kuantitas = implode(',', $request->input('kuantitas'));
$data->satuan_ukuran = implode(',', $request->input('satuan_ukuran'));
$data->status_pesanan = $request->get('status_pesanan');
$data->save();
Alert::success('Sukses!', 'Berhasil Menambahkan Pesanan!');
return redirect ('/daftar_paket');
}
}
The issue seems to be that you are trying to insert a value in the field id_paket that is too long. Check the type and size of id_paket and compare to what your query is sending: 18,18
You should not try to save arrays into a single field unless they are intended to be kept as a json.
I think you are trying to create two ModelPesanan? if so, assuming id_paket is a foreign key and the key of the id_paket array is the same for all the other arrays in the request then you can try:
DB::table('tbl_paket')
->where('id_paket',$id)
->update(['status_paket' => $request->status_paket]);
foreach($request->input('id_paket') as $index => $idPaket){
$data = new ModelPesanan();
$data->id_paket = $request->input('id_paket')[$index];
$data->kode_bmn = $request->input('kode_bmn')[$index];
$data->kode_unit = $request->input('kode_unit')[$index];
$data->jenis_barang = $request->input('jenis_barang')[$index];
$data->kuantitas = $request->input('kuantitas')[$index];
$data->satuan_ukuran = $request->input('satuan_ukuran')[$index];
$data->status_pesanan = $request->get('status_pesanan');
$data->save();
}
Alert::success('Sukses!', 'Berhasil Menambahkan Pesanan!');
return redirect ('/daftar_paket');

Encoding JSON with PHP from database table data

I want to be able to encode JSON into a specific format so that it can be used with another script that I have created. I am able to encode it with PHP into JSON but need to be able to push these encoded JSON sets to a 'named' array.
At the moment I am getting this
{
"ann_date":"14\/12\/2017",
"ann_title":"Return Dates",
"ann_content":"Have a good break. The course timetable resumes on Wednesday 3rd January 2018",
"tutor":"John Smith"
}
From this code
class AnnData {
public $ann_date = "";
public $ann_title = "";
public $ann_content = "";
public $tutor = "";
}
while($row = mysqli_fetch_array($result)) {
$ann_date = $row['ann_date'];
$ann_title = $row['ann_title'];
$ann_content = $row['ann_content'];
$tutor = $row['tutor'];
$annData = new AnnData();
$annData->ann_date = $ann_date;
$annData->ann_title = $ann_title;
$annData->ann_content = $ann_content;
$annData->tutor = $tutor;
$annQ = json_encode($annData);
But need it to look like this
{
"announcements":[{
"ann_date":"14\/12\/2017",
"ann_title":"Return Dates",
"ann_content":"Have a good break. The course timetable resumes on Wednesday 3rd January 2018",
"tutor":"John Smith"}]
}
You can declare an associative array and then encode it:
$annData = new AnnData();
...
$out = array('announcements' => array($annData));
$outJson = json_encode($out);
You can simplify this a lot by getting the correct columns from your database (only the 4 your need) and fetching all rows at once:
$annQ = json_encode([
'announcements' => mysqli_fetch_all($result, MYSQLI_ASSOC),
]);
This replaces all the code you have posted.
An associative array will be stored in the string as an object so you don't need that class either if you are not going to use it anywhere else.

Perform "javascript/jQuery-like" functions using PHP

I'm trying to move some processing from client to server side.
I am doing this via AJAX.
In this case t is a URL like this: https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2.
First problem, I need to send a bunch of these URLs through this little function, to just pull out "1081244497" using my example. The following accomplishes this in javascript, but not sure how to make it loop in PHP.
var e = t.match(/id(\d+)/);
if (e) {
podcastid= e[1];
} else {
podcastid = t.match(/\d+/);
}
The next part is trickier. I can pass one of these podcastid at a time into AJAX and get back what I need, like so:
$.ajax({
url: 'https://itunes.apple.com/lookup',
data: {
id: podcastid,
entity: 'podcast'
},
type: 'GET',
dataType: 'jsonp',
timeout: 5000,
success: function(data) {
console.log(data.results);
},
});
What I don't know how to do is accomplish this same thing in PHP, but also using the list of podcastids without passing one at a time (but that might be the only way).
Thoughts on how to get started here?
MAJOR EDIT
Okay...let me clarify what I need now given some of the comments.
I have this in PHP:
$sxml = simplexml_load_file($url);
$jObj = json_decode($json);
$new = new stdClass(); // create a new object
foreach( $sxml->entry as $entry ) {
$t = new stdClass();
$t->id = $entry->id;
$new->entries[] = $t; // create an array of objects
}
$newJsonString = json_encode($new);
var_dump($new);
This gives me:
object(stdClass)#27 (1) {
["entries"]=>
array(2) {
[0]=>
object(stdClass)#31 (1) {
["id"]=>
object(SimpleXMLElement)#32 (1) {
[0]=>
string(64) "https://itunes.apple.com/us/podcast/serial/id917918570?mt=2&uo=2"
}
}
[1]=>
object(stdClass)#30 (1) {
["id"]=>
object(SimpleXMLElement)#34 (1) {
[0]=>
string(77) "https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2"
}
}
}
}
What I need now is to pull out each of the strings (the URLs) and then run them through a function like the following to just end up with this: "917918570,1081244497", which is just a piece of the URL, joined by a commas.
I have this function to get the id number for one at a time, but struggling with how the foreach would work (plus I know there has to be a better way to do this function):
$t="https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2";
$some =(parse_url($t));
$newsome = ($some['path']);
$bomb = explode("/", $newsome);
$newb = ($bomb[4]);
$mrbill = (str_replace("id","",$newb,$i));
print_r($mrbill);
//outputs 1081244497
find match preg_match() and http_build_query() to turn array into query string. And file_get_contents() for the request of the data. and json_decode() to parse the json responce into php array.
in the end it should look like this.
$json_array = json_decode(file_get_contents('https://itunes.apple.com/lookup?'.http_build_query(['id'=>25,'entity'=>'podcast'])));
if(preg_match("/id(\d+)/", $string,$matches)){
$matches[0];
}
You may have to mess with this a little. This should get you on the right track though. If you have problems you can always use print_r() or var_dump() to debug.
As far as the Apple API use , to seperate ids
https://itunes.apple.com/lookup?id=909253,284910350
you will get multiple results that come back into an array and you can use a foreach() loop to parse them out.
EDIT
Here is a full example that gets the artist name from a list of urls
$urls = [
'https://itunes.apple.com/us/podcast/real-crime-profile/id1081244497?mt=2&uo=2.',
'https://itunes.apple.com/us/podcast/dan-carlins-hardcore-history/id173001861?mt=2'
];
$podcast_ids = [];
$info = [];
foreach ($urls as $string) {
if (preg_match('/id(\d+)/', $string, $match)) {
$podcast_ids[] = $match[1];
}
}
$json_array = json_decode(file_get_contents('https://itunes.apple.com/lookup?' . http_build_query(['id' => implode(',', $podcast_ids)])));
foreach ($json_array->results as $item) {
$info[] = $item->artistName;
}
print '<pre>';
print_r($info);
print '</pre>';
EDIT 2
To put your object into an array just run it through this
foreach ($sxml->entries as $entry) {
$urls[] = $entry->id[0];
}
When you access and object you use -> when you access an array you use []. Json and xml will parse out in to a combination of both objects and arrays. So you just need to follow the object's path and put the right keys in the right places to unlock that gate.

how to check if a word is repeated in string php [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a database that have multiple fields. i've to display one of its field in in html table. i can do it easily. but the problem is that the field i want to show may contain repeated words in a row. for eg
john;mike;john
john
mike;mike;mike
now what i want to do is that i have to trim repeated words i.e if a word is more than once in a row so it should be displayed only once. e.g above will be
john;mike
john
mike
i.e i don't want to show repetition when displaying record in html table. i want to make it dynamic i.e not just for 5 to 6 word. but to condemn repetition even if there thousands of records.
considering whole value of a row as a string how could i remove this using php ..
Thanks for your support in advance..
$variable="mike;john;mike";
$each=explode(';',$variable);
//print_r($each);
$new=array_unique($each);
echo implode(';',$new); //mike;john
If you'll treat each line or row as a sentence you can split on the separator, the semicolon in your examples. So if "UD;RUP;UD;UD" is a line you do something like:
line = "UD;RUP;UD;UD";
lineArray = new Array();
lineArray=line.split(";");
Then you want to create a new array that will hold the unique values you parse from your string:
newArray = new Array();
Now you iterate over the first array and see if you already have it stored. If you don't, store it by pushing to your new array:
for(i=0;i<lineArray .length;i++)
{
if((i==lineArray .indexOf(lineArray [i]))||(lineArray .indexOf(arr[i])==lineArray .lastIndexOf(arr[i])))
newArray.push(lineArray [i]);
}
And finally join the newArray elements:
newArray.join(";");
You can try with this
<?php
$consulta=Array('azul,azul,verde,amarillo','verde','azul,verde','azul');
$arrall=Array();
foreach ($consulta as $value) {
$arrnew= explode(",", $value);
if(count($arrnew!=0)){
foreach ($arrnew as $value) {
array_push($arrall, $value);
}
}
}
$result = array_unique($arrall);
I would say, the key is to create a unique index for each record.
<?php
$records = array(
'john;mike;john',
'john',
'mike;sally;mike;mike'
);
foreach($records as $index => $record) {
$records[$index] = implode(';',array_unique(explode(';',$record)));
}
print_r($records);
?>
This is in plain JavaScript to show the concept
var records = [
'john;mike;john',
'john',
'mike;sally;mike;mike'
]
var tuple;
for(var r in records) {
var tuple = records[r].split(';');
var index = {};
for(var t in tuple) {
index[tuple[t]] = true;
}
records[r] = Object.keys(index).join(';');
}
console.log(records);
I hope this helps :)
Try this:
/**
* #param array|string $values
* #param string $delimiter
*
* #return bool|string
*/
function filterValues($values = array(), $delimiter = ';') {
if(is_string($values) && $values) {
$explodedValues = explode($delimiter, $values);
return implode($delimiter, array_unique($explodedValues));
} else if(is_array($values) && $values) {
return implode($delimiter, array_unique($values));
} else {
return false;
}
}
$string= 'mike;bike;mike';
$array = array('mike', 'bike', 'mike');
echo filterValues($string);
echo filterValues($array);

Categories

Resources