I did not find similar question
1
$form['level1']['level2'][] = array(
'data' => 'some data',
'type' => 'some type',
);
//etc
2
$form = array(
'level1' => array(
'level2' => array(
array(
'data' => 'some data',
'type' => 'some type',
),
//etc
),
),
);
This is absolutely microoptimizing...
Test 1: 9.0906839370728
Test 2: 8.5538339614868
But the second is more efficient. For example [] is slower as it first has to check for the last index etc...
Also the first has to first check if the array already exists (at every dimension) while in the second case it is clear to PHP that there is a new array.
P.s.: But I don't really know, as the first is less to parse than the second. The parser time I didn't measure... (And I don't suppose that the arrays are now very often recreated?)
2 is more readable than 1.
Also, if you going to play without warning, 1 would be:
$arr = array();
$arr["level1"] = array();
$arr["level1"]["level2"] = array();
//... etc
Related
I'm saving some JSON and I don't know if this might later nib me in the butt if the JSON gets too big(The size depends on user input), though from my reading the max depth of 512 seems to be quite a high number and not really practical, but it triggered something in my mind and I've only now realized that I don't quite understand the meaning of "depth" of an array or how to count it (visually)...
I checked out this question while trying to get a clear understanding of depth: What is the purpose of using depth in JSON encode?
And the example given was:
array(
'foo',
'bar',
'baz'
)
// Has depth of 1
array(
array(
'foo'
),
array(
'bar'
),
array(
'baz'
)
)
// Has depth 2
But what about...
array(
array(
'foo'
),
array(
'bar'
),
array(
array(
'baz' => 'caz'
)
)
Or
array(
array(
'foo'
),
array(
'bar'
),
array(
array(
'baz' => 'caz'
),
array(
'tree' => array(
'tree-a' => array(
'car-a' => 'car-b'
)
)
)
)
I know this might be obvious to some but it's just one of those things I never thought much about. I did check out the documentation for json_decode() and it's depth parameter but still couldn't wrap my head around it. Maybe there's some rule of thumb i can use?
I'm trying to understand this in the context of when using json_decode();
Short: Is there a way to get a named key/value from SUBARRAY without knowing the main key ?
Long:
Ive got a foreach loop that extracts text-files & turns them into individual / single arrays (resetting the array between each file)...
example:
Array
(
[Blah Blah] => Array
(
[number] => 10
[name] => nameBlah
[image] =>
)
)
Array
(
[pinkblue597] => Array
(
[number] => 18
[name] => nameBlah68
[image] =>
)
)
(the 1st part to turn into array is used by multiple parts of a process so I dont want to add unnecessary code)
I want to extract the value of "name" and "number", however I do not know the value / format of the key in advance.. - Example: pinkblue597
If I do print_r, I do see the array as I want...
print_r($found,true)."\n";
but if I do this, $name=$found[0]; I get no results for "$name"...
or
if I do this, $name=$found[0]["name"]; I get no results for "$name"...
I could do this via a foreach loop, but it seems inefficient...
PS there will only be ONE (unknown) key in this array, & a sub-array. The sub array is always the same.
Edited: made the code easier to see (forgot to do this)
If the array formation is going to be the same all the time...
then a (nested) foreach loop will suffice, take the example below,
<?php
$a = [
'somethingUnknown13582563' => [
'name' => 'name',
'number' => 15
],
'somethingUnknown2' => [
'name' => 'another name',
'number' => 24
]
];
foreach ($a as $key => $subArray) {
foreach ($subArray as $subKey => $value) {
echo $subArray[$subKey] . '<br>';
}
}
?>
Output
name
15
another name
24
Or...
You could use array_values,
<?php
$a = [
'somethingUnknown13582563' => [
'name' => 'first name',
'number' => 15
],
'somethingUnknown2' => [
'name' => 'name',
'number' => 24
]
];
$a = array_values($a);
echo $a[0]['name'];
?>
Which would turn the first associative array in to numeric indexes and would like so,
array(
0 => array(
'name' => 'first name',
'number' => 15,
),
1 => array(
'name' => 'name',
'number' => 24,
)
)
I'm not sure why you're creating a nested array in the first place if you only intend to discard it immediately, but since the array only appears to have a single element, and you only care about that element, you can simple use array_pop
$a = [
'somethingUnknown13582563' => [
'name' => 'first name',
'number' => 15
],
];
$data = array_pop($a);
echo $data['name']; // gives you 'first name'
Note that array_pop is destructive. So if you don't want this behavior you could use something like end instead.
$data = end($a); // same effect as array_pop but non-destructive
echo $data['name']; // also gives you 'first name'
With that said, the foreach construct isn't necessarily inefficient. I believe your true concern is around finding a simpler way to dereference the nested array. The easiest way to do that in your case is going to be using something like end($a)['name'] which gives you the kind of straight-forward dereferencing you're looking for.
You can use array_map() to achieve this...
array_map — Applies the callback to the elements of the given arrays. This will loop all the array elements through callback function and you can print each element present in the sub array..
<?php
$myArry = array(
'Blah Blah' => array(
'number' => 10,
'name' => 'Blah Blah 1',
),
'pinkblue597' => array(
'number' => 15,
'name' => 'Blah Blah 2',
)
);
array_map(function($arr){
echo 'Name : '.$arr['name'].'<br>';
echo 'Number : '.$arr['number'].'<br>';
},$myArry);
?>
This will give you :
Name : Blah Blah 1
Number : 10
Name : Blah Blah 2
Number : 15
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";
I have array like this:
array(
'person0' => array( 'name'=>'name0','address'=>'address0' ),
'person1' => array( 'name'=>'name1','address'=>'address1' ),
'person2' => array( 'name'=>'name2','address'=>'address2' )
);
I want to change it like this. (just append a new value in each sub-array)
array(
'person0' => array( 'name'=>'name0','address'=>'address0','type'=>'type0' ),
'person1' => array( 'name'=>'name1','address'=>'address1','type'=>'type1' ),
'person2' => array( 'name'=>'name2','address'=>'address2','type'=>'type2' )
);
Is there any related function in php to perform this action? What is the shortest way to do this. Is it possible without loop?
Thanks
Browse the PHP manual when you wonder if a function exists to do something... it probably does.
http://www.php.net/manual/en/function.array-walk.php
http://php.net/manual/en/function.array-map.php
I'd just write the loop, but you can use those functions if you don't want to.
I've been playing around with Mongo for about a week now and I still can't work out how to modify nested arrays in Mongo with php.
So here is a sample document...
array (
'_id' => new MongoId("4cb30f560107ae9813000000"),
'email' => 'mo#maurice-campobasso.com',
'firstname' => 'Maurice',
'lastname' => 'Campobasso',
'password' => 'GOD',
'productions' =>
array (
0 =>
array (
'title' => 'a',
'date' => '1286811330.899',
),
1 =>
array (
'title' => 'b',
'date' => '1286811341.183',
),
2 =>
array (
'title' => 'c',
'date' => '1286811350.267',
),
3 =>
array (
'title' => 'd',
'date' => '1286811356.05',
),
),
)
What I wan't to do is delete an array inside the productions array, but I can't work out how. I've been playing with 'update('$pull' => ...etc)' but I haven't been able to make it work.
OK, there are a few ways to do this. In your case, I would do something like
mymongoobject.update( $unset : { "productions.2" : 1 } }
That's basically saying to unset the ".2" element of productions. Some docs here.
Now $pull should also work, but it's a little tougher because "productions" is actually an array of arrays (or objects with sub-objects). So you'd have to match arrays exactly:
mymongoobject.update( $pull : { "productions" : {'title':'d', 'date':'1286811356.05'} }
In the case above, the unset is probably the easiest option (though it will leave a "hole" in the array)
That is actually very easy, unlike traditional sql stuff you just modify the whole data and pass it back.
$cursor = $mongo->yourDB->yourCollection->findOne("_id",4cb30f560107ae9813000000);
//let's remove last item on productions
array_splice($cursor["productions"],2);
//and update the mongo document
echo $mongo->yourDB->yourCollection->update($cursor);
//it echoes 1 if successful
hope it helps.