I am calling the getTeams function below to get a simple list of team names but I can't get it to work without a 2 step process.
If I use
function getTeams($teams){
foreach ($teams as $team) {
$team = $team['team'];
$teamNames[] = $team['displayName'];
}
return $teamNames;
}
It looks like it is creating an associative array with the keys being numeric starting at 0?
I can make it work using
function getTeams($teams){
foreach ($teams as $team) {
$team = $team['team'];
$teamNames[] = $team['displayName'];
}
for ($i= 0; $i < count($teamNames); $i++){
$teamNames2[$teamNames[$i]]=$teamNames[$i];
}
return $teamNames2;
}
I think it might be because the first array is an associative Array and the second one is creating an indexed array? Is that thought process correct? If so, what is the correct way to create an indexed array in the foreach loop?
Without knowing your array: If you want to create an associative array you should give its element a key. So instead of
function getTeams($teams){
foreach ($teams as $team) {
$team = $team['team'];
$teamNames[] = $team['displayName'];
}
return $teamNames;
}
where the code
$teamNames[]
will add always an indexed entry to your array.
If you want a associative entry use a key instead. Something like
function getTeams($teams){
foreach ($teams as $team) {
$team = $team['team'];
$teamNames[$team['key']] = $team['displayName'];
}
return $teamNames;
}
$teamNames should now return an associative array
Related
So far I have a multidimen array results
foreach ($votes as $vote) {
$choices = array();
Foreach ($vote->getVoteChoicesOrdered() as $choice) {
array_push($choices, $choice->getAnswer()->getID());
}
array_push($results, $choices);
}
Later, I want to remove the first element of each choice in results and shift the positions back up (so I can remove the next element at [0] if I need to)
foreach ($results as $res) {
if (in_array(array_values($res)[0], $losers)) {
$shiftedRes = array_shift($res);
}
}
$losers is an array of array keys
Now that I have the shifted array, how would i go about replacing the current $result element with the new $shiftedRes? Something like $results[key($res)] = $shiftedRes?
Instead of shifting from your $res array, do it directly from the $results array.
foreach (array_keys($results) as $key)
{
if (in_array(array_values($results[$key])[0], $losers))
{
$shiftedRes = array_shift($results[$key]);
}
}
I am doing laravel project. I have one sql query as,
$catcount=2;
for($i=0;$i<$catcount;$i++) {
$subCat[] = Category::where('parent_id', '=', $userCategory[$i])->pluck('id');
}
$subCat returns an array as,
[[54,55,56,57,58],[48,49,50,51,52]]
I want this array as a single dimensional array like,
[54,55,56,57,58,48,49,50,51,52]
I am not getting how to do this, Please help and thanks in advance.
I suggest You to do ids merge before querying, so You will save some run time by accessing database only one time.
$catcount = 2;
$parents_ids = [];
for ($i = 0; $i < $catcount; $i++) {
$parents_ids[] = $userCategory[$i];
}
$subCats = Category::whereIn('parent_id', $parents_ids)->pluck('id');
$catcount=2;
for($i=0;$i<$catcount;$i++) {
$subCat[] = Category::where('parent_id', '=' $userCategory[$i])->pluck('id');
}
array_merge($subCat[0],$subCat[1]);
From your final array, you can just do an array merge
list($a1, $a2) = $subCat;
$subCat = array_merge($a1, $a2);
There are a lot of ways to do that. One of them: simple, but universal, readable and updatable (if something will change in your data structure, you'll be able to update this code in no time):
$newArr = [];
foreach ($subCat as $subArr) {
foreach ($subArr as $value) {
$newArr[] = $value;
}
}
if your array have multiple elements, you can merge them using this code:
$subCats = call_user_func_array("array_merge", $subCat);
I get my data from the database, but want to add 2 keys to them. So I add them in a for loop. If I dump (simple function that prints the array with pre tags) the single result in the for loop, it's correct, when I dump the 2dimensional array outside of it, it doesn't have the keys anymore..
For some reason it doesn't push it to the 2dimensional array?
$results is a 2dimensional array btw.
//add amount and subtotal to the array's elements
foreach ($results as $result) {
$result['amount'] = $sessionShoppingCart[$result['artikelnummer']][1];
$result['subtotal'] = $result['amount'] * $result['Verkoopprijs'];
$this->dump($result);
}
$this->dump($results);
To change an array within the foreach you can do two things.
Reference the array value with &:
foreach ($results as &$result) {
Or use the key and modify the array:
foreach ($results as $key => $result) {
$results[$key]['amount'] = $sessionShoppingCart[$result['artikelnummer']][1];
$results[$key]['subtotal'] = $result['amount'] * $result['Verkoopprijs'];
}
I have two queries:
1) $result = $this->_db->get_where("wishes",array("is_open"=>1))->result_array();
2) $requirements_result = $this->_db->get("requirements")->result_array();
I'm trying to output the data in this JSON format:
{
[
{
id:12,
title:"Meet Messi",
image_url:"http://dsadsa.dsadsa",
previewImageUrl:"http://kdjfla.com"
is_open:"true"
requirements: [
{
id: 123,
title:"kiss Messi",
is_complete: true
}
]
}
]
}
}
I created two models (one for each query).
This is what I've done so far:
$result = $this->_db->get_where("wishes",array("is_open"=>1))->result_array();
$requirements_result = $this->_db->get("requirements")->result_array();
$return_array = array();
foreach ($result as $value)
{
$wishes_model = new wishes_model();
$wishes_model->init_wishes($value);
$return_array[] = $wishes_model;
}
return $return_array;
How to i insert the requirements result to create this JSON?
First, create your wishes array as an associative array, with the ID as the key:
$wishes_array = array();
foreach ($results as $value) {
$wishes_model = new wishes_model();
$wishes_model->init_wishes($value);
$wishes_array[$value['id']] = $wishes_model;
}
Then you can add the requirements to the appropriate wish:
foreach ($requirements_results as $req) {
$wishes_array[$req['wish_id']]->requirements[] = $req;
}
I'm making some assumptions about which things in your application are associative arrays versus objects. You should be able to adjust this to match your specific implementation.
I have couple of question but for now i am gonna guess.
You can try array_merge but it will overwrite same keys.
If you don't want that you can add prefix to keys and then merge both array.
And i think rest of the solutions you already have in here.
Hi like you have 2 results say result1 and result2
you can make 2 foreach loop for each and store them in two different array and then
you make pass it in result and encode it.
see how it works:
foreach ($result1 as $res)
{
$result_s1[]=$res;
}
foreach($result2 as $cmd)
{
result_s1[]=$cmd;
}
$resultdata[]=array_merge($result_s1,$result_s2)
I need to work with a hashtable which values can store variables like:
$numberOfItems
$ItemsNames
If I ain't wrong, that would mean another hash like array as value.
What should be the right syntax for inserting and iterating over it?
Is anything like:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
valid?
if there's no chance to have collusion in item name, you can use the name in key
$hash[$ItemsName] = $numberOfItems;
in the other case, use an integer for example as a key, then the different "attributes" you want as keys for the 2nd array
$hash[$integer]["count"] = $numberOfItems;
$hash[$integer]["name"] = $name;$
Then, for iterating (1st case):
foreach ($hash as $name => $number) {
echo $number;
echo $name;
}
or, 2nd case
foreach ($hash as $item) {
echo $item["name"];
echo $item["count"];
}
To create php array, which can be a hash table, you can do:
$arr['element'] = $item;
$arr['element'][] = $item;
$arr['element'][]['element'] = $item;
Other way:
$arr = array('element' => array('element' => array(1)));
To iterate over it use foreach loop:
foreach ($items as $item) {
}
It's also possible to create nested loops.
About your case:
$hash['anyKey']=>$numberOfItems=15;
$hash['anyKey']=>$ItemsNames=['f','fw'];
I would do:
$hash['anyKey']['numberOfItems'] = 15;
$hash['anyKey']['ItemsNames'] = array('f','fw');