PHP foreach not behaving as expected - php

I have an array (POSTed from a Python application) called "observations". It looks like this:
Array
(
[0] => Array
(
['remote_id'] => 1
['dimension_id'] => 1
['metric'] => 1
)
[1] => Array
(
['remote_id'] => 1
['dimension'] => 2
['metric'] => 2
)
[2] => Array
(
['remote_id'] => 1
['dimension_id'] => 3
['metric'] => 3
)
(etc)
I want to iterate through all those instances of remote_id, dimension_id and metric and write them to a database. But I can't access them - here's my PHP:
foreach ($_POST["observations"] as $observation) {
echo "Let's try and access the whole array... \n";
print_r ($observation);
echo "But what about the sub elements? \n";
print_r ($observation[0]);
print_r ($observation['dimension_id']);
}
This returns:
Let's try and access the whole array...
Array
(
['remote_id'] => 1
['dimension_id'] => 1
['metric'] => 1
)
But what about the sub elements?
Let's try and access the whole array...
Array
(
['remote_id'] => 1
['dimension'] => 2
['metric'] => 2
)
But what about the sub elements?
(etc)
So my print_r ($observation[0]) and print_r ($observation['dimension_id']) are both failing to access the appropriate sub-elements and returning empty. What am I missing here?
Edit: a few questions about my (potentially malformed) POST. Doing it in Python like so:
data = urllib.urlencode([
("observations[0]['remote_id']", 1),
("observations[0]['dimension_id']", 1),
("observations[0]['metric']",metric1),
("observations[1]['remote_id']", 1),
("observations[1]['dimension']", 2),
("observations[1]['metric']", metric2),
("observations[2]['remote_id']", 1),
("observations[2]['dimension_id']", 3),
("observations[2]['metric']",metric3),
("observations[3]['remote_id']", 1),
("observations[3]['dimension_id']", 4),
("observations[3]['metric']",metric4),
("observations[4]['remote_id']", 1),
("observations[4]['dimension_id']", 5),
("observations[4]['metric']",metric5),
])
response = urllib2.urlopen(url=url, data=data)

This works according to your given array:
$array = Array(
0 => Array
(
'remote_id' => 1,
'dimension_id' => 1,
'metric' => 1
),
1 => Array
(
'remote_id' => 1,
'dimension_id' => 2,
'metric' => 2
),
2 => Array
(
'remote_id' => 1,
'dimension_id' => 3,
'metric' => 3
)
);
foreach ($array as $observation) {
echo "Remote id: ". $observation['remote_id']."<br />";
echo "Dimension id: ". $observation['remote_id']."<br />";
echo "Metric: ". $observation['metric']."<br />";
}
That will print:
Remote id: 1
Dimension id: 1
Metric: 1
Remote id: 1
Dimension id: 1
Metric: 2
Remote id: 1
Dimension id: 1
Metric: 3
But it looks like your $_POST["observations"] is not an array of $observation's but just one $observation.
There is probably something wrong in your form. Did you use arrays in your input like
<input type="text" name="observations[0]['metric']" />?

Related

Sum parts of an array in php

this is quite beyond me. Appreciate some help.
I have an array in php like so:
[0] => Array
(
[cust_id] => 1006
[no_of_subs] => 2
[dlv_id] => 1000
)
[1] => Array
(
[cust_id] => 1011
[no_of_subs] => 3
[dlv_id] => 1000
)
[2] => Array
(
[cust_id] => 1012
[no_of_subs] => 5
[dlv_id] => 1001
)
[3] => Array
(
[cust_id] => 1013
[no_of_subs] => 6
[dlv_id] => 1001
)
I don't need the cust_id field. I just need to group the dlv_id and the sum of no_of_subs for each matching dlv_id. The result should look like this:
[0] => Array
(
[dlv_id] => 1000
[no_of_subs] => 5
)
[1] => Array
(
[cust_id] => 1011
[no_of_subs] => 11
)
Thank you for any help.
I don't understand the downvotes for this question. Am i doing it all wrong? Downvoting without a reason is not helping.
The simplest, most efficient way to group and sum is to perform a single loop and assign temporary associative keys.
When a row is identified as a new dlv_id row, save the two desired elements, otherwise add the no_of_subs value to the pre-existing value.
Optionally, remove the temporary keys with array_values().
Code (Demo)
$array = [
["cust_id" => 1006, "no_of_subs" => 2, "dlv_id" => 1000],
["cust_id" => 1011, "no_of_subs" => 3, "dlv_id" => 1000],
["cust_id" => 1012, "no_of_subs" => 5, "dlv_id" => 1001],
["cust_id" => 1013, "no_of_subs" => 6, "dlv_id" => 1001]
];
foreach ($array as $row) {
if (!isset($result[$row["dlv_id"]])) {
$result[$row["dlv_id"]] = ["dlv_id" => $row["dlv_id"], "no_of_subs" => $row["no_of_subs"]];
} else {
$result[$row["dlv_id"]]["no_of_subs"] += $row["no_of_subs"];
}
}
var_export(array_values($result));
Output:
array (
0 =>
array (
'dlv_id' => 1000,
'no_of_subs' => 5,
),
1 =>
array (
'dlv_id' => 1001,
'no_of_subs' => 11,
),
)
Using array_column function, we can extract out dlv_id and no_of_subs separately in two different arrays, using cust_id as the key.
Now, simply loop over the array of dlv_id, and if matching key found, add the no_of_subs to it, else set the value (for the first time).
We use isset function to check if the key exists already or not.
Try the following:
// your input array is $input_array
// get all dlv_id maintaining the cust_id as index
$dlv_id = array_column($input_array, 'dlv_id', 'cust_id');
// get all no_of_subs maintaining the cust_id as index
$no_of_subs = array_column($input_array, 'no_of_subs', 'cust_id');
$output = array();
foreach ($dlv_id as $key => $value) {
if (isset($output[$value]['dlv_id'])) {
$output[$value]['dlv_id'] += $no_of_subs[$key];
} else {
$output[$value]['dlv_id'] += $no_of_subs[$key];
}
}

How to echo 5 Different Arrays?

I need to collect all the lines with the numbers, And turn them into str and then echo each one separately,
How can i do it please?
array (
0 =>
array (
0 => 'id=4321',
1 => '4321',
),
1 =>
array (
0 => 'id=7777',
1 => '7777',
),
2 =>
array (
0 => 'id=0101',
1 => '0101',
),
3 =>
array (
0 => 'id=1213',
1 => '1213',
),
)
Example:
4321
7777
0101...
Maybe:
echo $you_array[0][1]."<br>";
echo $you_array[1][1]."<br>";
echo $you_array[2][1]."<br>";
.....................
You can also use nl2br(), google it or stackoverflow it.
-Edit:
or better:
foreach ($your_array as $subarr) {
echo $subarr[1]."<br>";
}

Access the array value

Array
(
['data'] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
['id'] => Array
(
[0] => 5
[1] => 6
[2] => 7
[3] => 8
)
)
This data ($form_data) coming from form. How to accessing this array? I cannot access with following:
$data= $form_data['data'][0]; or
$id = $form_data['id'][0];
I just accessing with array_values() function and following:
$data= $form_data[0][0]; or
$id = $form_data[0][0];
But i dont want use array_values() function. Why I cant access my array natural way?
This works fine man, make sure you are building your array correctly. This code works flawlessly. There's not much information on how you built the array, so I hope this model helps you.
<?php
$array = array(
'data' => array
(
0 => 'a',
1 => 'b',
2 => 'c',
3 => 'd'
),
'id' => array
(
0 => 5,
1 => 6,
2 => 7,
3 => 8
)
);
Now you can call back on your array using your preferred method:
$a = $array['data'][0];
$b = $array['data'][1];
$c = $array['data'][2];
echo $a . $b . $c;
// outputs 'abc'
Also call the id:
$fiv = $array['id'][0];
$six = $array['id'][1];
$sev = $array['id'][2];
echo $fiv . $six . $sev;
// outputs '567'

Sort PHP array by numerical values

I would like to sort the following names
Array ( [Jessie] => 2 [Sarah] => 3 [Simon] => 2 [John] => 2 [Kevin] => 1 [Canvasser] => 8 [canvasser] => 11 )
based on the values corresponding to them
I printed the names through the following function
// get canvasser individual names and count houses canvassed
foreach ($canvassers as $key => $value) {
// Add to the current group count if it exists
if ( isset( $canvasser_counts[$value] ) ) {
$canvasser_counts[$value]++;
}
// or initialize to 1 if it doesn't exist
else {
$canvasser_counts[$value] = 1;
}
}
print_r($canvasser_counts);
where $canvassers simply held all the names eg.
$canvassers = array('Jessie', 'Simon', 'Jessie')
Any help would be really appreciated, I have spent so long on this but can't get my head straight to sort the array correctly.
You want to use asort() - http://php.net/manual/en/function.asort.php - to sort the values in ascending order, or arsort() - http://php.net/manual/en/function.arsort.php - to sort in descending order.
Given this PHP:
$vals = array("Jessie" => 2, "Sara" => 3, "Simon" => 2, "John" => 2, "Kevin" => 1, "Canvasser" => 8, "canvasser" => 11 );
print_r($vals); // current order
asort($vals); // sort array
print_r($vals); // new order
You will get the following output:
Array
(
[Jessie] => 2
[Sara] => 3
[Simon] => 2
[John] => 2
[Kevin] => 1
[Canvasser] => 8
[canvasser] => 11
)
Array
(
[Kevin] => 1
[Jessie] => 2
[John] => 2
[Simon] => 2
[Sara] => 3
[Canvasser] => 8
[canvasser] => 11
)

Splitting one Array into many Array in PHP

I'm in need of splitting of the single array into multiple array for some report generating purpose.
I have an array like this which I have given below.
Array
(
[blah_1] => 1
[blahblah_1] => 31
[blahblahblah_1] => 25
[blah_3] => 1
[blahblah_3] => 3
[blahblahblah_3] => 5
[blah_10] => 1
[blahblah_10] => 10
[blahblahblah_10] => 2
)
I want to split the above to,
Array
(
[blah_1] => 1
[blahblah_1] => 31
[blahblahblah_1] => 25
)
Array
(
[blah_3] => 1
[blahblah_3] => 3
[blahblahblah_3] => 5
)
Array
(
[blah_10] => 1
[blahblah_10] => 10
[blahblahblah_10] => 2
)
How can I do this in PHP ??
$oldarray=array('blah_1'=>1,'blahblah_1'=>31,'blahblahblah_1'=>25,
'blah_3'=>1,'blahblah_3'=>3,'blahblahblah_3'=>5,
'blah_10'=>1,'blahblah_10'=>10,'blahblahblah_10'=>2
)
$newarray=array();
foreach ($oldarray as $key=>$val) { //Loops through each element in your original array
$parts=array_reverse(explode('_',$key)); //Splits the key around _ and reverses
$newarray[$parts[0]][$key]=$val; //Gets the first part (the number) and adds the
//value to a new array based on this number.
}
The output will be:
Array (
[1]=>Array
(
[blah_1] => 1
[blahblah_1] => 31
[blahblahblah_1] => 25
)
[3]=>Array
(
[blah_3] => 1
[blahblah_3] => 3
[blahblahblah_3] => 5
)
[10]=>Array
(
[blah_10] => 1
[blahblah_10] => 10
[blahblahblah_10] => 2
)
)
Use array_chunk. Example:
<?php
$chunks = array_chunk($yourarray, 3);
print_r($chunks);
?>
Use array_chunk
i.e
$a = array(1,2,3,4,5,6,7);
var_dump(array_chunk($a, 3));
Not sure if you are looking for array_slice
but take a look at this example:
<?php
$input = array("a", "b", "c", "d", "e");
print_r(array_slice($input, 2, -1));
print_r(array_slice($input, 2, -1, true));
?>
will result in this:
Array
(
[0] => c
[1] => d
)
Array
(
[2] => c
[3] => d
)
array_chunk ( array $input , int $size);

Categories