Just need a little help here about my problem. I am trying to create a simple update in a textfile.
My goal is:
If the data is existed in the textfile. Don't add a new line in the file instead update that certain line.
If data is not existed simple add a new line in the file.
I have a problem in updating. I used the array_replace() function to do this but it always add a new line. My updates are always appending to the textfiles.
Here's my code I hope that you can help me.
//This is the new array from the user
$data_add = array(
'restaurant_id' => $restaurant_id,
'new_lat' => $new_lat_entry,
'new_long' => $new_long_entry,
'date_updated' => date('Y-m-d H:i:s')
);
//This is the base array - It will get the text file if exsited
$data = unserialize(file_get_contents('addresses.txt'));
//get the ID of the new array - use for validation
$target = $data_add['restaurant_id'];
//loop the abase array
for ($i = 0; $i < count($data); $i++) {
//get the ID of the base array
$get_id = $data[$i]['restaurant_id'];
//compare base array ID and new array ID
if($get_id == $target){
// IF FOUND IN THE TEXTFILE
$add_data = array();
$add_data = array(
$i => $data_add
);
//replace the existed array in textfile with my updated array
$new_array = array();
$new_array = array_replace($data,$add_data);
//break;
}else{
//IF NOT FOUND, SIMPLY ADD
$new_array = array(
$i => $data_add
);
//fn_print_die($new_array);
}
}
//FOR DISPLAYING PURPOSES
echo "<pre>";
echo "BASE ARRAY<br />";
print_r($data);
echo "---------------------------------------------------------<br />";
echo "NEW ARRAY<br />";
print_r($add_data);
echo "---------------------------------------------------------<br />";
echo "REPLACED ARRAY<br />";
print_r($new_array);
echo "---------------------------------------------------------<br />";
//exit;
//SERIALIZE THE UPDATED ARRAY
$serialize_data = serialize($new_array);
//WRITE THE TEXTFILE
$file_input_txt = fopen("addresses.txt","a+");
fwrite($file_input_txt,$serialize_data);
fclose($file_input_txt);
//exit;
$array = unserialize(file_get_contents('addresses.txt'));
$file_input = fopen("addresses.csv","a+");
fputcsv($file_input, $data_add);
fclose($file_input);
Related
I have 2 array in my code, like the shown below:
<?php
$kalimat = "I just want to search something like visual odometry, dude";
$kata = array();
$eliminasi = " \n . ,;:-()?!";
$tokenizing = strtok($kalimat, $eliminasi);
while ($tokenizing !== false) {
$kata[] = $tokenizing;
$tokenizing = strtok($eliminasi);
}
$sumkata = count($kata);
print "<pre>";
print_r($kata);
print "</pre>";
//stop list
$file = fopen("stoplist.txt","r") or die("fail to open file");
$stoplist;
$i = 0;
while($row = fgets($file)){
$data = explode(",", $row);
$stoplist[$i] = $data;
$i++;
}
fclose($file);
$count = count($stoplist);
//Cange 2 dimention array become 1 dimention
for($i=0;$i<$count;$i++){
for($j=0; $j<1; $j++){
$stopword[$i] = $stoplist[$i][$j];
}
}
//Filtering process
$hasilfilter = array_diff($kata,$stopword);
var_dump($hasilfilter);
?>
$stopword contain of some stop word like attached in http://xpo6.com/list-of-english-stop-words/
All I wanna do is: I want to check if save the element that exist in array $kata and it is not exist in array $stopword
So I want to delete all the element that exist in both array $kata and $stopword .
I read some suggestion to use array_diff , but somehow it doesn't work to me. Really need your help :( Thanks.
array_diff is what you need, you are right. Here is a simplified version of what you try to do:
<?php
// Your string $kalimat as an array of words, this already works in your example.
$kata = ['I', 'just', 'want', 'to', '...'];
// I can't test $stopword code, because I don't have your file.
// So let's say it's a array with the word 'just'
$stopword = ['just'];
// array_diff gives you what you want
var_dump(array_diff($kata,$stopword));
// It will display your array minus "just": ['I', 'want', 'to', '...']
You should also double check the value of $stopword, I can't test this part (don't have your file). If it does not work for you, I guess the problem is with this variable ($stopword)
There is a problem in your $stopword array. var_dump it to see the issue.array_diff is working correct.
Try following code I wrote to make your $stopword array right:
<?php
$kalimat = "I just want to search something like visual odometry, dude";
$kata = array();
$eliminasi = " \n . ,;:-()?!";
$tokenizing = strtok($kalimat, $eliminasi);
while ($tokenizing !== false) {
$kata[] = $tokenizing;
$tokenizing = strtok($eliminasi);
}
$sumkata = count($kata);
print "<pre>";
print_r($kata);
print "</pre>";
//stop list
$file = fopen("stoplist.txt","r") or die("fail to open file");
$stoplist;
$i = 0;
while($row = fgets($file)){
$data = explode(",", $row);
$stoplist[$i] = $data;
$i++;
}
fclose($file);
$count = count($stoplist);
//Cange 2 dimention array become 1 dimention
$stopword= call_user_func_array('array_merge', $stoplist);
$new = array();
foreach($stopword as $st){
$new[] = explode(' ', $st);
}
$new2= call_user_func_array('array_merge', $new);
foreach($new2 as &$n){
$n = trim($n);
}
$new3 = array_unique($new2);
unset($stopword,$new,$new2);
$stopword = $new3;
unset($new3);
//Filtering process
$hasilfilter = array_diff($kata,$stopword);
print "<pre>";
var_dump($hasilfilter);
print "</pre>";
?>
I hope it helps
This question already has answers here:
php json_encode not working on arrays partially
(2 answers)
Closed 7 years ago.
I am trying to properly create and encode and array using json_encode php function. The array i am trying to encode is $myarray . From my code if do
$myarray = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval())) ;
then
echo json_encode($myarray) ; // this works but only one item is pushed to my array
if i do
$myarray[] = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval //pushing all elements to array
result is nothing.
what i am missing ?
see full code below on what i have so far done.
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
/*
* Retrieve available Room types.
* TODO
* make accessing ids automatic..
*/
include_once("../../openerp_models.php"); // include file to connect with openerp
date_default_timezone_set('Europe/Moscow'); // Timezone settings
//openerp connection details
require_once("../../connection.php") ;
try {
//we access partner model and domain for customers only
$customer = $connection_model->search('res.partner', 'customer', '=', TRUE);
//
//create an array
$ids = array();
//create a for loop and loop through the ids from search
for($i = 0; $i <= count($customer); $i++ )
{
// assign array values
$ids [] = $customer[$i] ;
}
// read partner with $ids
$customer_details = $connection_model->read('res.partner', $ids);
//loop through the scalavar value
$myarray = null;
// loop through the value returned
foreach ($customer_details as $keys => $values)
{
$value = $values->scalarval();
//Push values to my array
$myarray [] = array(array('name' =>$value['display_name']->scalarval(),'id' => $value['id']->scalarval())) ;
//
}
//Then try to encode $myrray but this fails
$jsonstring = json_encode($myarray);
if ($jsonstring!==false)
{
echo $jsonstring;
} else {
echo 'Could not properly encode $myarray';
}
///////////////////////
/////////////////////////
}
catch(Exception $ex){
print "Error ".$ex.getMessage() ;
}
?>
please help. thank you.
The right way to create the array would be like this:
$myarray = array(
array(
'name' => 'bla',
'id' => 1
), array(
'name' => 'blas',
'id' => 2
)
);
This part of your code is perfectly fine.
$data = array() ; //create new empty array
//loop through the array
foreach($myarray as $keys => $h)
{
$data [] = $h;
}
//encode
echo json_encode($data) ; //this fails silently
If you run the code, it works perfectly fine:
[{"name":"bla","id":1},{"name":"blas","id":2}]
Your foreach() loop creates a new array $data with the same entries (also arrays) as the $myarray contains. So, you could directly encode $myarray like this:
<?php
$myarray = array(
array('name' =>' Agrolait', 'id' => 6 ),
array('name' => 'Agrolait, Michel Fletcher', 'id' => 31 ),
array('name' => 'Agrolait, Thomas Passot', 'id' => 30 )
);
$jsonstring = json_encode($myarray);
if ($jsonstring!==false) {
echo $jsonstring;
} else {
echo 'Could not properly encode $myarray';
}
?>
Which produces this JSON string:
[{"name":" Agrolait","id":6},{"name":"Agrolait, Michel Fletcher","id":31},{"name":"Agrolait, Thomas Passot","id":30}]
json_encodereturns the value FALSE if something went wrong, and the encoded string else. If you check the result from it you at least know when it fails.
Thanks for your suggestion have solved this. My string data was not properly encoded using utf-8 as suggested by http://nl3.php.net/manual/en/function.json-encode.php. Check my answer below
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
/*
* Retrieve available Room types.
* TODO
* make accessing ids automatic..
*/
include_once("../../openerp_models.php"); // include file to connect with openerp
date_default_timezone_set('Europe/Moscow'); // Timezone settings
//openerp connection details
require_once("../../connection.php") ;
try {
//we access partner model and domain for customers only
$customer = $connection_model->search('res.partner', 'customer', '=', TRUE);
//
//create an array
$ids = array();
//create a for loop and loop through the ids from search
for($i = 0; $i <= count($customer); $i++ )
{
// assign array values
$ids [] = $customer[$i] ;
}
// read partner with $ids
$customer_details = $connection_model->read('res.partner', $ids);
//loop through the scalavar value
$myarray = null;
// loop through the value returned
foreach ($customer_details as $keys => $values)
{
$value = $values->scalarval();
$myarray [] = array('name' =>utf8_encode($value['display_name']->scalarval()),'id' => utf8_encode($value['id']->scalarval())) ;
//
//array_push($better, $myarray) ;
}
//echo '<pre>';
//print_r($myarray) ;
//echo '</pre>';
echo json_encode($myarray);
exit;
}
catch(Exception $ex){
print "Error ".$ex.getMessage() ;
}
?>
I have a problem. I want to put dates into an array but when I make print_r() I get only the last value from checkbox.
My code is:
$id = Input::get('id');
$aObjects = Input::get('aObjects');
$iCount = count($aObjects);
for($i=0; $i < $iCount; $i++)
{
$test = array ($aGoupes = array(
'idGroupe' => $id,
'idObject' => $aObjects[$i]
));
}
echo '<pre>';
print_r($test);
echo '</pre>';
The output is:
Array
(
[0] => Array
(
[idGroupe] => 6
[idObject] => 8
)
)
So the problem is that only the last value checked from checkbox is put in this table. Please help me!! Thnx
Your problem is that you're resetting $test each time.
Try this:
$id = Input::get('id');
$aObjects = Input::get('aObjects');
$iCount = count($aObjects);
$test = array();
for ($i = 0; $i < $iCount; $i++) {
$test[] = array (
'idGroupe' => $id,
'idObject' => $aObjects[$i]
);
}
echo '<pre>';
print_r($test);
echo '</pre>';
I'm not too sure what your code is supposed to do, but the idGroupe will always be the same in each array, as you're setting it to $id which is never changed. That may well be correct, though.
I am pulling results from an LDAP query with php. One of the items in the array of results is an array with 3 sets of information. How do I make it display all three sets instead of just the first? See my code below:
if ($ds) { $ds=ldap_connect("ldap-server");
$r=ldap_bind($ds);
$sr=ldap_search($ds, "DC=,DC=co,DC=uk",$search);
$info = ldap_get_entries($ds, $sr)or die('get info fail');
$header = array(
t('Picture'),
t('First Name'),
t('Last Name'),
t('Role'),
t('Email')
);
$rows = array();
for ($i=0; $i<$info["count"]; $i++) {
//Handle Image
if(isset($info[$i]["jpegphoto"][0])){
$tempFile = tempnam(sys_get_temp_dir(), 'image');
file_put_contents($tempFile, $info[$i]["jpegphoto"][0]);
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = explode(';', $finfo->file($tempFile));
$jpeg = '<img src="data:' . $mime[0] . ';base64,' . base64_encode($info[$i]["jpegphoto"][0]) . '"/>';
}else{
$path = drupal_get_path('module','search_engine');
$jpeg = '<img src="'.$path.'/images/userImage.jpg" />';
}
$rows[$i] = array(
'picture' => $jpeg,
'first' => $info[$i]["givenname"][0],
'last' => $info[$i]["sn"][0],
'role' => $info[$i]["memberof"][0],
'mail' => $info[$i]["mail"][0],
);
}
ldap_close($ds);
return theme('table', array('header'=>$header,'rows'=>$rows));
I'm showing picture, first, last, role, and email in my table. Role contains an array with 3 items, how do I make it go through every item in the array? I know I can't just throw a foreach into the middle of an array.
I need to display all of these.
If you don't need to do anything with the individual roles in that sub-array, e.g. display it only, then simply implode() it into a string:
$rows[$i] = array(
...
'roles' => implode(',', $info[$i]['memberof'])
...
);
If you do need do some with the individual components, then deal with it separately:
$rows[$i] = array(...normal non-array data here);
foreach($info[$i]['memberof'] as $key => $value) {
$rows[$i]['role'][$key] = $value;
}
Are you looking for something like implode()?
$roles = array("role1","role2","role3");
$imploded = implode(",", $roles);
echo $imploded; //should return "role1,role2,role3"
I have a problem in my code. My code is all about updating/deleting rows in textfile ig the textfile is found. I am having a trouble with it. At first I can add a new textfile and together with it I can also update this file. But it is for 1 row. If I update another row. It will just append the updated value at the end of the textfile. What I want is to update this or delete and insert the new one. But I don't know how. My process in updating the array is array_replace(). First I need to find out if the ID of my data is found in the textfile. If found I will simple update/delete and replace the existing data into my new updated data. If not found just add only.
Here's my code for that.
$restaurant_id = $post_data['company_id'];
$new_lat_entry = $post_data['new_lat'];
$new_long_entry = $post_data['new_long'];
/****Here's my new updated array ****/
$data_add = array(
'restaurant_id' => $restaurant_id,
'new_lat' => $new_lat_entry,
'new_long' => $new_long_entry,
'date_updated' => date('Y-m-d H:i:s')
);
/****This is the BASE array from the existing textfile ****/
$data = unserialize(file_get_contents('addresses.txt'));
$target = $data_add['restaurant_id'];
for ($i = 0; $i < count($data); $i++) {
$get_id = $data[$i]['restaurant_id'];
if($get_id == $target){
//If ID is found - UPDATE
$add_data = array();
$add_data = array(
$i => $data_add
);
$new_array = array();
$new_array = array_replace($data,$add_data);
$serialize_data = serialize($new_array);
$file_input_txt = fopen("addresses.txt","w+");
fwrite($file_input_txt,$serialize_data);
fclose($file_input_txt);
}else{
$new_array = array(
$i => $data_add
);
$serialize_data = serialize($new_array);
$file_input_txt = fopen("addresses.txt","w+");
fwrite($file_input_txt,$serialize_data);
fclose($file_input_txt);
}
}
The output of my text file is in serialized form.
a:1:{i:0;a:4:{s:13:"restaurant_id";s:4:"1519";s:7:"new_lat";s:8:"14.63823";s:8:"new_long";s:9:"121.02999";s:12:"date_updated";s:19:"2013-11-15 12:42:59";}}
That's all guys please help me. I have a deadline now. And I am stuck with it. :-( This is the first time I am creating a CRUD based on a text file that's why I am having a trouble debugging it.
Can you please try this,
<?php
/****This is the BASE array from the existing textfile ****/
$data = unserialize(file_get_contents('addresses.txt'));
$restaurant_id = '1519';
$new_lat_entry = '14.64823';
$new_long_entry = '121.45999';
/****Here's my new updated array ****/
$data_add = array(
'restaurant_id' => $restaurant_id,
'new_lat' => $new_lat_entry,
'new_long' => $new_long_entry,
'date_updated' => date('Y-m-d H:i:s')
);
$target = $data_add['restaurant_id'];
$Count =count($data);
$new_array =array();
for ($i = 0; $i < $Count; $i++) {
$get_id = $data[$i]['restaurant_id'];
//If ID is found - UPDATE
$add_data = array(
$i => $data_add
);
if($get_id == $target){
$new_array = array_replace($data,$add_data);
}
}
$serialize_data= serialize($new_array);
print_r($serialize_data);
$file_input_txt = fopen("addresses.txt","w+");
fwrite($file_input_txt, $serialize_data);
fclose($file_input_txt);
?>