I have an array named 'users' in which I am storing some variables as you see below.I want to verify if the 'nume' (name) value already existing in this array is the same as the value introduced by a person in a search box. I've tried some methods but I haven't obtained the wanted result. I think it is something obvious I can't see at the moment.
EDIT : The image is the result of var_dump() of my code. I am using it for people to understand what I want to know.
it's simple, try that:
$searchValue = 'victor';
$index = array_search($searchValue, array_column($users, 'nume'));
Related
What I need to do is to export as as .csv a list of a lot of different values inside different entities. I need each reference created at a certain date with related values.
What I did was first, find all the objects by date and put them in an array.
$parcelRepo = $this->getDoctrine()->getRepository(Parcel::class);
$dateToday = new \DateTime("now");
$parcels = $parcelRepo->findBy([
'date_add' => $dateToday
]);
Then, in a foreach loop, I find the values that relates to each parcel entity. This is where I have a problem, I don't understand how to access the values which are not located in the same table as my first parcel entity.
I need to not use SQL as well.
Here is the code where I get the "Only variables should be passed by reference" error.
$array = [];
foreach ($parcels as &$p) {
$array.array_push(
$p->getDeliveryOrder()->getProduct()->getAccount()->getCoclico(),
"1",
"",
$p->getDeliveryOrder()->getUser()->getLogin(),
$p->getDeliveryOrder()->getProduct()->getCode(),
$p->getInternalReference(),
$p->getDeliveryOrder()->getProduct()->getCode()+"0"+$p->getNumber(),
"121",
$p->getName(),
$p->getAddress4(),
$p->getAddress1(),
$p->getAddress2(),
$p->getAddress3(),
"téléphone", //TODO
$p->getPostalCode(),
$p->getCity(),
\DateTime::createFromFormat('Ymd',$dateToday),
"",
"",
"0"
);
}
I think I need to use QueryBuilder but was wondering if there was any other way to do what I need since QueryBuilder is close to SQL (from what I understand).
Also, as I need to export each foreach values in one line, I need a multidimensional array. However I did not look into this issue since I can't even get the values I need.
So the issue comes from
$array.array_push(
this code actually merges $array and array_push() returning value, array_push() first parameter should be the array ( which is sent through reference) you want to push in, and because you are actually sending a value and not a variable, this error appears.
Here is the documentation for array_push https://www.php.net/manual/ro/function.array-push.php
so it should actually be
array_push($array, ...);
But as Ricardo left you a comment, this code is not really necessary, you can get the formatted data like this from a query, chaining multiple relation calling like:
$p->getDeliveryOrder()->getProduct()->getAccount()->getCoclico()
is not really desirable, but if you think you can't do that then the fix is just to write array_push correctly.
I simply want to know how to access array elements retrieved from a database. I have the following code to get the names of each item in my database.
$plat_options = $this->db->get('tblplatform_options')->select('name')->result();
How do I go about accessing the name from the array $plat_options? Typically I would do $plat_options[0] for the first element in C#, how is this done in php/codeigniter?
In PHP/Codeigniter, can be done in the same way:
$plat_options[0] //if you have this element, usually is better to check if exists.
You can retrieve all the elements with foreach($plat_options as $option){...}
You can cast to object: https://www.kathirvel.com/php-convert-or-cast-array-to-object-object-to-array/
Or use a Codeigniter Helper (assuming you are using CI3): http://www.codeigniter.com/user_guide/helpers/array_helper.html
I recomend to know which is your array format and retrieve that way (if you don't know, you can do a: var_dump($plat_options) ) to know if is an associative array.
You can use the result_array() function:
$data = $plat_options->result_array();
echo($data[0]['name']);
or:
$data = array_shift($q->result_array());
echo($data['name']);
I extracted this last part from: Codeigniter $this->db->get(), how do I return values for a specific row? that you could check too.
If you don't know a lof of CI, the best you can do is do a simple tutorial to understand how the data + ActiveRecord works.
Hope it helps!
I am trying to merge a static data with json encode array data for output. Here is my php code:
$arr = array();
$rs = mysql_query("SELECT id, name, picture, mail, gender, birthday FROM users WHERE id='$logged_id' ");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"users":'.json_encode($arr).'}';
Now I want to merge other data with it:
$user_ip = array("user_ip" => $user_ip_address);
I have tried array_merge($arr, $user_ip). But it didn't work. I think this is not correct json array format if I merge with existing data array. Please let me know what to do how to output other data as well as current data coming from mysql with json encode.
I am getting such output with my existing code, which is correct:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11"}]}
But now I want to add other variable e.g $user_ip_address as user's data joining with current output data like this:
{"users":[{"id":"14","name":"Sonu Roy","picture":"image012.jpg","mail":"myemail#gmail.com","gender":"Male","birthday":"1983-01-11",user_ip:"127.0.0.1"}]}.
I want to get it in this way. How to do it? Please let me know. Thanks in advance.
try this:
echo json_encode(array('users' => $arr, 'user_ip' => $user_ip_address));
on a side note:
you should use PHP PDO class to connect and query the database.
mysql_fetch_object returns an object, not an array. So, what are you doing by $arr[] = $obj; is just adding an object into an array. So, the actual structure of the $arr is something like
$arr => [
[0] => Object(....),
[1] => Object(....),
....
]
In your particular case, I assume you are fetching single row by primary key, so there are only one object.
THe simpliest way to fix this is to add a field to an object. I haven't worked with PHP since 5.3, so can't be sure, but it's as simple as adding
$obj->user_ip = $user_ip_address;
inside the loop.
Btw, a couple of questions for you:
Why do you use loop if it should result in a single row?
Why you are embedding the variable directly into SQL query. It's quite vulnerable, read about sql-injections and how to prevent it (one day I was really tired telling people here on SO to use PDO and prepared statements, so just go read about it),
Have you read the documentation about mysql_fetch_object and array_merge? Why not (because if you have read it you wouldn't be asking the question).
Tried debugging? E.g. attaching a debugger and watching for variables contents? Inserting logging or (God forgive me) debug print with echo?
"Didn't work" is a quite bad error description. This time you was lucky, because the error was obvious. Next time, please, be more specific.
I'm working on a project where all of the members and their info are stored in a JSON file. I'm in the process of creating a search form and I need help on how to iterate through the members and check to see if there's an exact match or a similar match.
The members are stored in a SESSION variable:
$_SESSION['members'] = json_decode($jsonFile);
but I'm uncertain how to use regex to check for matches that are similar (and not just exact). For example, if a member's name is "Jonathan", I'd like that result to be returned even if the user searches "Jon". Is regex the correct approach? Any help will be greatly appreciated - thank you!
-Manoj
I think I'd be using a database to store the data rather than JSON so that you can use the LIKE searches, e.g.
SELECT * FROM users WHERE name LIKE 'Jon%'
If you absolutely have to use JSON you could loop through all members and use a regexp like
preg_match('/^'.$term.'.*/i', $element, $matches);
to check them all.
If the $jsonFile contents is an array of some sort, you may find preg_grep() of use, though it doesn't work on multidimensional arrays. You might have have to loop over each individual member record and grep the relevant fields yourself, something like:
foreach ($_SESSION['members'] as $idx => $member) {
... match relevant fields...
}
I don't really know how to decribe this problem, so I'm sorry if the title is a bit unclear.
I got an object with array fields. I got the name of these fields stored in a variable and I want to reach an element in one of those array fields. e.g.
$field_name = 'array_field';
$object = new stdClass();
$object->array_field= array('this', 'is', 'an', 'array);
I know i can access the array with $object->$field_name, but now I want to access a value by key in the array while accessing it with the $field_name variable. e.g.(that obviously does not work) $object->$field_name[0]
I think, you should use something like the following:
$object->{$field_name}[0]
It's described in details in "Variable variables" section of PHP manual: http://www.php.net/manual/en/language.variables.variable.php
BTW, according to my experience, such way of fields manipulation may lead to code obscurity - I'd recommend to use associative arrays, if possible.
Try this:
$object->{$field_name}[0]