I have the assoc array alldept.
I want now the 'name' element from the array with the id e.g. '1';
How do I access the id and output the 'name'?
The id is saved in $result[$i]['abteilung']
Thank you very much!
$manager = $this->getDoctrine()
->getManager('olddb')
->getRepository('ChrisOldUserBundle:BpDepartment');
$dept = $manager->findBy([],['name' => 'ASC']);
$alldept = array();
foreach ($dept as $singledpt){
$alldept[] = array("id" => $singledpt->getId(),
"name" => $singledpt->getName()
);
}
As you are building this array yourself it would seem sensible to build it in a way that is later usable.
So why not build the array like this
$manager = $this->getDoctrine()
->getManager('olddb')
->getRepository('ChrisOldUserBundle:BpDepartment');
$dept = $manager->findBy([],['name' => 'ASC']);
$alldept = array();
foreach ($dept as $singledpt) {
$alldept[ $singledpt->getId() ] = $singledpt->getName();
}
Now if you know you want the name of dept = 1 you just do
echo $alldept[1];
What I would suggest is to keep id as key and name as value:
$manager = $this->getDoctrine()
->getManager('olddb')
->getRepository('ChrisOldUserBundle:BpDepartment');
$dept = $manager->findBy([],['name' => 'ASC']);
$alldept = array();
foreach ($dept as $singledpt){
$alldept[$singledpt->getId()] = $singledpt->getName();
}
Note: I am assuming getId will be unique
Then to fetch name, you can simply type $alldept[$id].
This might not be an answer, just an alternative. You can avoid a loop.
Related
I need to create an array out of two arrays. I tried to use array_merge but it doesn't work.
With the first array, I pull all IDS of custom posts.
$all_posts = get_posts(array(
'fields' => 'id',
'posts_per_page' => -1,
'post_type' => 'items'
));
$ids = array();
foreach($all_posts as $a){
$id[] = array("id"=>$a->ID);
}
With second array I get only items assigned to that page:
$items = get_field('items');
$assigned_items= array();
foreach($items as $p){
$id = $p["select_item"][0]->ID;
$price= $p["price"];
$live = $p["live"];
$assigned_items[]=array("id"=>$id, "price"=>$available, "live"=>$live);
}
$price and $live variables are boolean.
Now I need to create an array out of these two. As the first array pulls all items, I need to merge with id in the second array. $price and $live could be one true one false.
I need to create an array with all ids from $ids array and add $price and $live elements to it from the second array if the ids are the same. If id doesn't exist in the second array, both price and live are false in the final output.
You need something like this, I also made some improvement to your code and check if there is any post or item before loop (to avoiding warning from php) also better error handling.
<?php
$ids = $assigned_items = $merged = array();
$all_posts = get_posts(array(
'fields' => 'id',
'posts_per_page' => -1,
'po|st_type' => 'items'
));
if($all_posts) {
foreach($all_posts as $a){
// $id[] = array("id"=>$a->ID);
$merged[$a->ID]["id"] = $a->ID;
}
$items = get_field('items');
if($items) {
foreach($items as $p){
$id = $p["select_item"][0]->ID;
$price= $p["price"];
$live = $p["live"];
// $assigned_items[]=array("id"=>$id, "price"=>$available, "live"=>$live);
$merged[$id]["price"] = $price;
$merged[$id]["live"] = $live;
} else {
// no item ...
}
}
} else {
// no post ...
}
if you assign your second iteration object, to the key in the array, you can easily merge them.
$assigned_items[$p["select_item"][0]->ID] = ['id' => $id, 'price' => $available, 'live' => $live];
Now you could join them, by accessing the assigned items by the id. Combining the arrays with the + operator.
foreach ($all_posts as $post) {
$combined = (array) $post + $assigned_items[$poost->ID] ?? [];
}
This would also eliminate you, from doing the $ids iteration.
I wrote an api call in my Symfony project that returns all fields from my entity with the query defined below..
Now, I need to define just three fields like 'id', 'name', 'value' and to pull values from that fields that are currently stored in a database.
public function getChartData() {
$myResults = $this->getMyRepository()
->createQueryBuilder('s')
->groupBy('s.totalCollected')
->orderBy('s.id', 'ASC')
->getQuery()
->getArrayResult();
$result = array("data" => array());
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
}
The problem is it return just totalCollected field.
One of errors are Call to a member function getId() on array and so on, and I can't figure out a way to pull data from db...
I cannot see in your code where $schoolResult come from but lets guess it string key of some sort.
Notice you trying to set 3 value on the same key so only the last one remains.
Look at:
$a = array();
$a["key"] = 4;
$a["key"] = 6;
It is simple to see that $a["key"] will contains 6 and not 4 or both.
When you do:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult] = $label["id"];
$result['data'][$schoolResult] = $label["name"];
$result['data'][$schoolResult] = $label["totalCollected"];
}
You override the data in $result['data'][$schoolResult] therefor only try totalCollected is there as the last one to set.
In order to fix that you can use:
foreach ($myResults as $myResult => $label) {
$result['data'][$schoolResult]["id] = $label["id"];
$result['data'][$schoolResult]["name"] = $label["name"];
$result['data'][$schoolResult]["totalCollected"] = $label["totalCollected"];
}
Hope that helps!
I have a database with project entries. Each entry has a project title, datestamp, the user who entered it, and a comment. I am trying to format this data as JSON for reporting and charts.
I want an array for each project name, and inside that array an array for each entry.
I've tried several approaches but I haven't had much luck yet.
if ($result = $mysqli->query("SELECT * FROM project_entries"))
// WHERE WEEK(date) = WEEK(current_date) ORDER BY project_name
{
while ($row = mysqli_fetch_array($result)) {
$entry_array = array();
$row_array['project_name'] = $row['project_name'];
$comment = $row['comment'];
$entry = array (
'comment' => $comment,
);
$row_array['entries'] = $entry;
if ( !in_array($row['project_name'], $projects, false ))
{
array_push($projects, $row_array);
}
}
}
Outputs:
[
{
"project_name": "Logo Design",
"entries": {
"comment": "Worked on a thing"
}
},
{
"project_name": "Logo Design",
"entries": {
"comment": "Created some stuff"
}
},
While I want:
{
"project_name": "Logo Design",
"entries": {
"comment": "Worked on a thing",
"comment": "Created some stuff"
}
}
This should do the trick. You can use the project name as an array key. In order to prevent the string keys from showing up in your output array, you can use array_values to convert them to numeric keys.
$projects = array();
while ($row = mysqli_fetch_array($result)) {
$projects[$row['project_name']]['project_name'] = $row['project_name'];
$projects[$row['project_name']]['entries'][] = array('comment' => $row['comment']);
}
echo json_encode(array_values($projects));
What was going wrong with your previous code:
if ($result = $mysqli->query("SELECT * FROM project_entries")) {
while ($row = mysqli_fetch_array($result)) {
$entry_array = array(); // This does not appear to be used
// With each iteration of the while loop, you create a new array of
// project information (project name and entries array with one comment)
$row_array['project_name'] = $row['project_name'];
$comment = $row['comment'];
$entry = array ('comment' => $comment);
$row_array['entries'] = $entry;
// The $projects array is an array of arrays, but $row['project_name'] is
// a string. Checking if this string is in an array of arrays will always
// be false, so the array_push should always execute.
if (!in_array($row['project_name'], $projects, false )) {
// Adds the new project array to the projects array
array_push($projects, $row_array);
}
// This is not producing what you want because you are adding a new
// array to $row_array each time the loop runs
}
}
Why the code I suggested works:
$projects = array(); // Empty array to hold all the projects
while ($row = mysqli_fetch_array($result)) {
// Using the project name from the database as an array key in the array we are
// constructing keeps the projects unique in that array.
// The first time a new project name occurs, this will create a new sub-array
// within $projects with project_name => the new project name. This value will
// be overwritten on subsequent occurrences of the same project name.
$projects[$row['project_name']]['project_name'] = $row['project_name'];
// For each iteration, this will add a comment to the 'entries' array in the
// project array with the key $row['project_name'].
$projects[$row['project_name']]['entries'][] = array('comment' => $row['comment']);
// For example, with the first iteration of the array we create the following:
//
// $projects['Logo Design'][
// 'project_name' =>'Logo Design',
// 'entries' => [0 => ['comment' => 'Worked on a thing'] ] ]
//
// with the second iteration, the project name is overwritten (with same project name)
// and another comment array is added to the entries array
//
// $projects['Logo Design'][
// 'project_name' =>'Logo Design',
// 'entries' => [0 => ['comment' => 'Worked on a thing'],
// 1 => ['comment' => 'Created some stuff'] ] ]
}
// If you just did echo json_encode($projects), you would not get the format you want,
// because of the string keys. Try it without the array_values() to see what I mean.
echo json_encode(array_values($projects));
Maybe something like that?
Use project id to build target array.
while ($row = mysqli_fetch_array($result) {
if (!isset($projects[$row['id']]))
{
$projects[$row['id']] = [
'project_name' => $row['project_name'],
'entries' => [],
];
}
$projects[$row['id']]['entries'][] = [
'comment' => $row['comment'],
];
}
Im using a function to share a collection of bookmarks with other users and i need to get the id after the new item is created in wordpress userpro bookmarks plugin
function share_collection($id,$name,$cbcolor,$user) {
$user_id = get_user_by( 'email', $user );
$user_id_current = get_current_user_id();
$collectionscurrent = $this->get_collections($user_id_current);
$collections = $this->get_collections($user_id->ID);
$collections[] = array('label' => $name);
// transfer bookmarks to shared collection
foreach($collectionscurrent[$coll_id] as $k => $arr) {
if ($k != 'label') {
$collections["This is where id should go"][$k] = 1;
}
}
update_user_meta($user_id->ID, '_wpb_collections', $collections);
}
How do i retrive the id created from $collections[] = array('label' => $name); and use it in the place where i mentioned "This is where id should go"
get_collections function is as follows
function get_collections($user_id) {
return (array)get_user_meta($user_id, '_wpb_collections', true);
}
Thanks in advance!
It's called array index. Assuming $collections is zero based numerical array without any "holes" in it (hole would be eg index 1 in [0 => 'a', 2 => 'b']), you can use:
$collections[] = array('label' => $name);
$idx = count($collections) - 1;
If it's not numerical or there can be holes, you have to figure out index to use first:
$idx = count($collections);
$collections[$idx] = array('label' => $name);
I have an array with structure generated like this:
$groups = array();
while ($group = mysql_fetch_array($groups_result)) {
$groups[] = array( 'id' => $group['id'], 'name' => $group['name']);
}
How can I later in the code get the name of the group by its id? For example, I would like a function like:
function get_name_by_id($id, $array);
But I'm looking for some solution which is already implemented in PHP. I know it would be easier to make arrays with array[5] = array('name' => "foo") etc where 5 in this case is id, but in my code there is a lot of arrays already created like i mentioned above and I cannot easily switch it.
$groups = array();
while ($group = mysql_fetch_assoc($groups_result)) {
$groups[$group['id']] = array( 'name' => $group['name']);
}
$name = $groups['beer']['name'];
also please not using fetch_assoc is more efficient than fetch array
function get_name_by_id($id, $data) {
foreach($data as $d) {
if ($d['id'] == $id) {
return $d['name'];
}
}
// return something else, id was not found
}