I am trying to add up a specific variable (gq_numplayers) and display it. How can I do that if the arrays are in an array?
I am using GameQ (https://github.com/Austinb/GameQ/) if you don't understand what is going on.
EDIT:
var_dump ($results);
http://pastebin.com/BSeeWMEb
<?php
// Include the main class file
require '../GameQ.php';
// Define your servers,
// see list.php for all supported games and identifiers.
$servers = array(
array(
'id' => 'server 1',
'type' => 'css',
'host' => '216.52.148.30',
),
array(
'id' => 'server 2',
'type' => 'css',
'host' => '216.52.143.83',
),
array(
'id' => 'server 3',
'type' => 'teamspeak3',
'host' => 'voice.xenogamers.org:8730',
)
);
// Init the class, only need this once
$gq = new GameQ();
$gq->addServers($servers);
//optional settings
$gq->setOption('timeout', 3); // Seconds
$gq->setOption('debug', TRUE);
// You can optionally specify some output filters,
// these will be applied to the results obtained.
$gq->setFilter('normalise');
// Send requests, and parse the data
$results = $gq->requestData();
//make total
$total = array_sum(?!?!?!??!?!?);
echo $results['server 1']['gq_numplayers'];
?>
Just loop through the servers and add the number of players to a running total.
$num_players = 0;
foreach ($results as $server) {
$num_players += (int)$server['gq_numplayers'];
}
If you have $ArrayB inside $ArrayA, then you need a loop. Loop through $ArrayA with foreach like this:
foreach ($ArrayA as $item) {
}
Inside that loop, you need to add the code to operate on $item. So each time the loop iterates, $item will be the next item in the array! You can add them all up with a variable declared before entering the loop such as $counter.
But I am also noticing you indicated this:
echo $results['server 1']['gq_numplayers'];
That is NOT an array in an array. That is a single two-dimensional array. So my answer wouldn't even apply directly to it. You'd have to change the loop somewhat.
You could try adding it yourself via array_walk().
I'm not sure about the $results structure after the requestData() call but let's assume it looks like the sample array below:
<?php
$results= array(
array(
'something' => 'text',
'gq_numplayers' => 1,
),
array(
'something' => 'text',
'gq_numplayers' => 2,
),
array(
'something' => 'text',
'gq_numplayers' => 3,
),
);
$total=0;
array_walk($results,function($value,$key) use(&$total) {
$total+=(int)$value['gq_numplayers'];
});
print $total."\n";
Related
I want to remove an item from an array. I can write this:
$item = array(
'id' => 1
'name' => 'name'
);
$item2 = $item;
unset($item2['id']);
$names[] = $item2;
but the last 3 lines are somewhat "cumbersome", soo un elegant. Can it be solved without creating $item2 ? Something like:
$item = array(
'id' => 1
'name' => 'name'
);
$names[] = array_ignore_index('id', $item);
From your codes, I can see that you are trying to get the names[] from item array. One possible simple solution for this specific scenario:
For example IF you have :
$items = array(
array(
//this is your item 1
'id' => 1,
'name' => 'name1'
),
array(
//this is item 2
'id' => 2,
'name' => 'name2'
)
);
and you want to retrieve the names in the names array.
You can just do:
$names = array_column($items, 'name');
It will return:
Array
(
[0] => "name1"
[1] => "name2"
)
Please note this solution is best fit for this specific scenario, it may not fit your current scenario depending.
The shortest out of the box solution is to create a diff of the array keys:
$names[] = array_diff_key($item, array_flip(['id']));
See http://php.net/array_diff_key.
function array_ignore_index($id,$item){ ///function
unset($item[$id]);
return $item;
}
$a=array('id'=>1,
'name'=>'name');
$b=array_ignore_index('name',$a);
echo $b['name']; //create error id is not present
Here is the code for required operation..
You can use unset array column
Code is
unset($item['id']);
To test it
print_r($item);
I get() an multidimensional array and store it inside the $products variable.
I need to Make a copy of that array to create it into a new Webshop because the export provided by the API does not work so I have created this script to copy the data:
foreach ($products as $id => $product) {
$copy = $products[$id];
$createdProducts = $apiSkylux->products->create(
array(
'id' => $copy['id'],
'createdAt' => $copy['createdAt'],
'updatedAt' => $copy['updatedAt'],
'isVisible' => $copy['isVisible'],
'visibility' => $copy['visibility'],
'data01' => $copy['data01'],
'data02' => $copy['data02'],
'data03' => $copy['data03'],
'url' => $copy['url'],
'title' => $copy['title'],
'fulltitle' => $copy['fulltitle'],
'description' => $copy['description'],
'content' => $copy['content'],
'set' => $copy['set'],
'brand' => $copy['brand'],
'categories' => $copy['categories'],
'deliverydate' => $copy['deliverydate'],
'image' => $copy['image'],
'images' => $copy['images'],
'relations' => $copy['relations'],
'reviews' => $copy['reviews'],
'type' => $copy['type'],
'attributes' => $copy['attributes'],
'supplier' => $copy['supplier'],
'tags' => $copy['tags'],
'variants' => $copy['variants'],
'movements' => $copy['movements'],
)
);
}
The copy is working. But i thought #2016 and all, can't this be achieved with less lines of code?
This is what I receive with var_dump of the first array:
var_dump($products[0]);
exit;
//result
array(28) {
["id"]=>
int(26136946)
//rest of array
So I can see the array has a number (28) , what does this represent?
I've tried several attempts, closest attempt was :
$copy = $products[$id];
$createProducts = $products;
$createdProducts = $apiSkylux->products->create($createProducts);
But then I also got an error : Invalid data input
Can I copy the data from the array easier then the method I am currently using?
array(
'id' => $copy['id'],
...
)
This can be reduced to simply:
$copy
Yes, reassigning every single key into a new array is the same as using the original array in the first place.
foreach($products as $id => $product){
$copy = $products[$id];
This can be reduced to:
foreach ($products as $product){
$copy = $product;
Obviously you could leave out $copy entirely and just use $product.
Bottom line:
foreach ($products as $product) {
$createdProducts = $apiSkylux->products->create($product);
}
What you do with $createdProducts I don't know; you don't seem to be doing anything with it inside the loop, so at best it'll hold the last product after the loop, so is probably superfluous.
Probably you could do:
array_map([$apiSkylux->products, 'create'], $products);
or
$createdProducts = array_map([$apiSkylux->products, 'create'], $products);
depending on whether you need the return values or not.
So I can see the array has a number (28) , what does this represent?
It means it's an array with 28 elements in it.
This doesn't make any sense. Simply use the $product variable within the loop. Done!
I'm writing a php web application where I have a nested array which looks similar to the following:
$results = array(
array(
array(
'ID' => 1,
'Name' => 'Hi'
)
),
array(
array(
'ID' => 2,
'Name' => 'Hello'
)
),
array(
array(
'ID' => 3,
'Name' => 'Hey'
)
)
);
Currently this means that when I want to use the ID field I have to call $results[0][0]['ID'] which is rather inefficient and with an array of over several hundred records becomes messy quickly. I would like to shrink the array down so that I can call $results[0]['ID'] instead.
My understanding is that a function that uses a foreach loop to iterate through each row in the array and change the format would be the best way to go about changing the format of the $results array but I am struggling to understand what to do after the foreach loop has each initial array.
Here is the code I have so far:
public function filterArray($results) {
$outputArray = array();
foreach ($results as $key => $row) {
}
return $outputArray;
}
Would anyone be able to suggest the most effective way to achieve what I am after?
Thanks :)
Simply use call_user_func_array as
$array = call_user_func_array('array_merge', $results);
print_r($array);
Demo
im currently trying to generate a dynamic subnavigation. Therefor i pull data off of the database and store some of it an an array. Now i want to do an foreach in this array. Well as far as I know, this isn't possible.
But maybe I'm wrong. I would like to know if it would be possible, and if so how do i do it?
This is my code, which wont work since it hands out an syntax error.
$this->subnav = array(
'' => array(
'Test Link' => 'login.php',
'Badged Link' => array('warning',10023,'check.php')
),
'benutzer' => array(
'Benutzer suchen' => '/mother/index.php?page=benutzer&subpage=serach_user',
'Benutzer hinzufügen' => '/mother/index.php?page=benutzer&subpage=add_user',
'Rechtevergabe' => '/mother/index.php?page=benutzer&subpage=user_rights'
),
'logout' => array(
'Login' => '/mother/login.php',
'Logout' => '/mother/index.php?page=logout'
),
'datenbank' => array(
(foreach($this->system->get_databases() as $db){array($db->name => $db->url)}),
'Deutschland' => '/mother/login.php',
'Polen' => '/mother/index.php',
'Spanien' => '/mother/index.php',
'Datenbank hinzufügen' => '/mother/index.php?page=datenbank&subpage=add_database'
)
);
}
You can't place foreach loop inside an array like this. You can do something like this though.
foreach($this->system->get_databases() as $db)
{
$this->subnav['datenbank'][$db->name] = $db->url;
}
This is not possible. but you can do it in other way like you can place the foreach outsite and top of this array and assign to an array and then you can use that array variable.
e.g.
$arrDB = array();
foreach($this->system->get_databases() as $db) {
$arrDB[$db->name] = $db->url;
}
Now assign it to:
'datenbank' => $arrDB
I'm trying to fill an array and I want to add some logic in it so it won't give me back errors...
Here is the code:
$entries_mixes = array();
foreach ($entries_query->result_array() as $entry) {
$entries_mixes[] = array('title' => $entry['title'],
'body' => $entry['body'],
'author' => $entry['author'],
'date_time' => $entry['date_time'],
'id' => $entry['id'],
'mix_name' => $mix['name'],
'photo_name' =>$photo['name']
);
}
what I want to do is to be able to check if some of the variables exist before I put them into the array....
so for example if(isset($mix['name'])) then insert to array or else do nothing
The point is not having undeclared variables trying to be inserted to my array cause it gives back errors...thanks!
You can use the ? : ternary operator:
$entries_mixes[] = array(
'title' => (isset($entry['title']) ? $entry['title'] : null),
'author' => (isset($entry['author']) ? $entry['author'] : null),
...
alternatively, use empty() for the check
You could use the ternary operator so that if the variables don't exist, NULL is used as the value. But you actually want to omit certain keys from the array altogether in that case. So just set each key separately:
$entry[] = array();
...
if (isset($mix['name'])) {
$entry['mix_name'] = $mix['name'];
}
...
$entries_mixes[] = $entry;
The following will check if title doesn't exists in the entry array or if it's blank. If so, it'll skip the entry completely and continue to the next element in the loop.
$entries_mixes = array();
foreach ($entries_query->result_array() as $entry) {
if (empty($entry['title'])) {
continue;
}
$entries_mixes[] = array('title' => $entry['title'],
'body' => $entry['body'],
'author' => $entry['author'],
'date_time' => $entry['date_time'],
'id' => $entry['id'],
'mix_name' => $mix['name'],
'photo_name' =>$photo['name']
);
}