Here is the output of some complex multidimensional array:
Array (
[0] => Array (
[#attributes] => Array ( [ID] => 114037469 [Name] => MJBDESIGN.ORG [Traffic] => 4 [BidCount] => 0 [Price] => $8 USD [ValuationPrice] => - [TimeLeft] => 3H 27M [RowID] => 1 )
)
[1] => Array (
[#attributes] => Array ( [ID] => 114136929 [Name] => TRAININGPROGRAMMEDESIGN.COM [Traffic] => 11 [BidCount] => 0 [Price] => $8 USD [ValuationPrice] => $3 USD [TimeLeft] => 3H 27M [RowID] => 2 )
)
)
How to iterate through each item and get the 'ID', 'Name' and etc of individual item? Thanks
This array is not so much complex.
$simpleArray = __YOUR_COMPLEX_ARRAY__;
foreach ($simpleArray as $array) {
$id = $array['#attributes']['ID'];
$name = $array['#attributes']['Name'];
}
foreach ($array as $r) {
$name = $r['#attributes']['Name'];
$id = $r['#attributes']['ID'];
# code ....
}
If you would like all attributes of each row:
foreach ($array as $n=>$r){
echo "Row {$n}\n";
foreach ($r as $k=>$v){
// Echo the data
echo "{$k}=>${v}\n";
}
}
Just easy way:
$array = // your long array;
foreach($array as $row)
{
$id = $row['#attributes']['Id'];
$name = $row['attributes']['Name'];
// do something with these variables
}
Try it like,
foreach ($yourarray as $val) {
echo $id = $val['#attributes']['ID'];
echo $name = $val['#attributes']['Name'];
}
Related
I have a multidimensional array as below:
$rows[] = $row;
Now I want to create variable from looping this array. This is how I tried it:
foreach ($rows as $k => $value) {
//echo '<pre>',print_r($value).'</pre>';
$id = $value['news_id'];
$title = $value['news_title'];
echo $title;
}
But it produce an error as below:
...... Illegal string offset 'news_id'
This is the output of - echo '<pre>',print_r($value).'</pre>';
Array
(
[news_id] => 1110
[news_title] => test
[news] => test des
)
1
Array
(
[news_id] => 1109
[news_title] => ශ්රී ලංකාවේ ප්රථම....
[news] => දහසක් බාධක....
)
1
Can anybody tell me what is the wrong I have done?
UPDATE
output for echo '<pre>',print_r($rows).'</pre>';
Array
(
[0] =>
[1] => Array
(
[news_id] => 1110
[news_title] => test
[news] => test des
)
[2] => Array
(
[news_id] => 1109
[news_title] => ශ්රී ලංකාවේ ප්රථම....
[news] => දහසක් බාධක....
)
)
1
use isset function because your 0 index is empty in $row
foreach ($rows as $k => $value) {
if(isset($value['news_id'])){
$id = $value['news_id'];
$title = $value['news_title'];
echo $title;
}
}
you should add check (condition) when you assign data to $rows
My arrays are
$name=>
Array
(
[0] => General
[1] => General
[2] => Outdoors
[3] => Dining
[4] => Dining
[5] => Kitchen
[6] => Kitchen
)
$key1=>
Array
(
[0] => 1
[1] => 2
[2] => 7
[3] => 11
[4] => 12
[5] => 17
[6] => 18
)
Array function
foreach ($key1 as $key => $value1) {
foreach ($name as $key => $value) {
echo $value "=>" $value1 ;
//echo "$value1";
}
}
Here I would like to print the values by using the same keys
if $name having the index as [0] and my $key1 also take the [0] value
i.e: my result should be in the form of
General => 1
General => 2
Outdoors => 7
Dining => 11
Dining => 12
Kitchen => 17
Kitchen => 18
You only need to iterate one array, not both of them:
foreach ($name as $key => $name_value) {
echo "$name_value => " . $key1[$key];
}
You can use a simple for loop to do this
for ($i = 0; $i < count($name); $i++) {
echo $name[$i] . '=>' . $key[$i]
}
The problem with your code is you're using the same variable $key for both foreachs, so the last one overwrites the value.
foreach ($key1 as $key => $value1) {
foreach ($name as $key => $value) {
echo $value "=>" $value1 ;
//echo "$value1";
}
}
You could make things easier by combining those two arrays, making $name array be the keys and $key1 array be the values
$newArray = array_combine($name, $key1);
foreach ($newArray as $name => $key) {
echo "{$name} =>{$key}";
}
This will work for you
<?php
$a1= array('General','Outdoors','Dining ');
$a2= array('1','2','3');
$newArr=array();
foreach($a1 as $key=> $val)
{
$newArr[$a2[$key]]= $val;
}
echo "<pre>"; print_r($newArr);
?>
output
Array
(
[1] => General
[2] => Outdoors
[3] => Dining
)
I am afraid this wont be possible if you want the output as associative array as same key name in an associative array is not allowed. It would be always overwritten if you are dealing with the associative arrays.
Although you may have something like this:
array_map(function($key, $val) {return array($key=>$val);}, $name, $key1)
Output:
Array ( [0] => Array ( [General] => 1 ) [1] => Array ( [General] => 2 ) [2] => Array ( [Outdoors] => 7 ) [3] => Array ( [Dining] => 11 ) [4] => Array ( [Dining] => 12 ) [5] => Array ( [Kitchen] => 17 ) [6] => Array ( [Kitchen] => 18 ) ).
But if you want the output in string format It is possible.
for ($i = 0; $i < count($key); $i++) {
echo $name[$i] . '=>' . $key[$i].'<br>';
}
Just change the foreach as follows...
foreach ($key1 as $key => $value1) {
echo $name[$key] ."=>". $value1."<br>";
}
replace the <br> with \n if you're running through the linux terminal. Also don't miss the '.' operator to concatenate the string..
Nested foreach won't do what you need... Good luck..
This question already has answers here:
Group array data on one column and sum data from another column
(5 answers)
Closed 9 months ago.
I have the following array
Array (
[0] => Array
(
[0] => ALFA
[1] => 213
)
[1] => Array
(
[0] => ALFA
[1] => 151
)
[2] => Array
(
[0] => ALFA
[1] => 197
)
[3] => Array
(
[0] => BETA
[1] => 167
)
[4] => Array
(
[0] => ZETA
[1] => 254
)
[5] => Array
(
[0] => GAMA
[1] => 138
)
[6] => Array
(
[0] => GAMA
[1] => 213
)
)
And I would like to group the key[0] of the subarray so I can see how many equal keys it has.
Something like that:
ALFA => 3
BETA => 1
EPSI => 1
GAMA => 2
I tried with array_count_values, but without success.
foreach ($array as $value) {
echo '<pre>';
print_r(array_count_values($value));
echo '</pre>';
}
With that we have following result:
Array
(
[ALFA] => 1
[213] => 1
)
Array
(
[ALFA] => 1
[151] => 1
)
...
Array
(
[GAMA] => 1
[213] => 1
)
And after that I would like to sum the values of each group as well.
ALFA => 213 + 151 + 197
BETA => 167
ZETA => 254
GAMA => 138 + 213
I think that when we solve the first part of the problem, the second would follow easier with quite the same method.
The final purpose is to divide the sum of values by the number of occurrences of each key group, so we can have an average of the values just like that:
ALFA => (213+151+197) / 3 = 187
BETA => 167
ZETA => 254
GAMA => (138+213) / 2 = 175,5
This is not the main problem, but as I said, I'm stuck with the beginning of the solution and would appreciate any help.
I'm surprised at all the long and complicated answers. However, the initial foreach to model your data to something manageable is needed. After that you just need to do a really simple array_walk.
<?php
$result = array();
foreach ($array as $el) {
if (!array_key_exists($el[0], $result)) {
$result[$el[0]] = array();
}
$result[$el[0]][] = $el[1];
}
array_walk($result, create_function('&$v,$k', '$v = array_sum($v) / count($v);'));
?>
Result:
Array
(
[ALFA] => 187
[BETA] => 167
[ZETA] => 254
[GAMA] => 175.5
)
Solution for you is here:
Code:
$input = [
['alfa', 123],
['alfa', 223],
['alfa', 122],
['alfa', 554],
['alfa', 34],
['dalfa', 123],
['halfa', 223],
['dalfa', 122],
['halfa', 554],
['ralfa', 34]
];
$result = [];
foreach ($input as $node) {
if (isset($result[$node[0]])) {
$result[$node[0]] = ['sum' => $result[$node[0]]['sum'] + $node[1], 'count' => $result[$node[0]]['count'] + 1];
} else {
$result[$node[0]] = ['sum' => $node[1], 'count' => 1];
}
}
print_r($result);
foreach ($result as $key => &$data) {
$data = $data['sum'] / $data['count'];
}
print_r($result);
Output:
Array
(
[alfa] => Array
(
[sum] => 1056
[count] => 5
)
[dalfa] => Array
(
[sum] => 245
[count] => 2
)
[halfa] => Array
(
[sum] => 777
[count] => 2
)
[ralfa] => Array
(
[sum] => 34
[count] => 1
)
)
Array
(
[alfa] => 211.2
[dalfa] => 122.5
[halfa] => 388.5
[ralfa] => 34
)
$sort = array();
foreach ($array as $value) {
$sort[$value[0]][] = $value[1];
}
then you count how many keys each has
$keys = array();
foreach($sort as $k => $v) {
$keys[$k] = count($v);
}
then for calculating the amount
$sum = array();
$average = array();
foreach($sort as $k => $v) {
$amount = 0;
foreach($v as $val) {
$amount += $val;
}
$sum[$k] = $amount;
$average[$k] = $amount / $keys[$k];
}
HOWEVER, If you want all the details in one array:
$final = array();
foreach ($array as $value) {
$final[$value[0]]["values"][] = $value[1];
}
foreach($final as $k => $v) {
$final[$k]["amount"] = count($v['values']);
$amount = 0;
foreach($v['values'] as $val) {
$amount += $val;
}
$final[$k]["sum"] = $amount;
$final[$k]["average"] = $amount / $final[$k]["amount"];
}
example: http://jdl-enterprises.co.uk/sof/25789697.php
Includes Output
Just copy the codes to your favorite text editor, sure it works perfectly.
$items = [
['ALFA',213],
['ALFA',151],
['ALFA',197],
['BETA',167],
['ZETA',254],
['GAMA',138],
['GAMA',213]
];
echo '<pre>' . print_r($items,true) . '</pre>';
$result;
foreach ($items as $value) {
# code...
if (isset($result[$value[0]])) {
$sum = $result[$value[0]]['sum'] + $value[1];
$count = $result[$value[0]]['count'] + 1;
$result[$value[0]] = ['sum' => $sum , 'count' => $count, 'divided' => ($sum / $count)];
} else {
$result[$value[0]] = ['sum' => $value[1] , 'count' => 1 , 'divided' => ($value[1] / 1) ];
}
}
echo '<pre>' . print_r($result,true) . '</pre>';
$myArray = [
["ALFA",213],
["ALFA",151],
["ALFA",197],
["BETA",167],
["ZETA",254],
["GAMA",138],
["GAMA",213]
];
$a1 = array(); //TEMPORARY ARRAY FOR KEEPING COUNT & TOTAL VALUES
$res = array(); //ARRAY USED TO KEEP RESULT
foreach($myArray as $val)
{
//AVOID PESKY NOTICES FOR UNDEFINED INDEXES
if ( !array_key_exists($val[0],$a1) ) {
$a1[$val[0]] = array("count" => 0,"total" => 0);
$res[$val[0]] = 0;
}
//INCREMENT THE COUNT OF INSTANCES OF THIS KEY
$a1[$val[0]]["count"]++;
//INCREMENT THE TOTAL VALUE OF INSTANCES OF THIS KEY
$a1[$val[0]]["total"]+=$val[1];
// UPDATE RESULT ARRAY
$res[$val[0]] = $a1[$val[0]]["total"] / $a1[$val[0]]["count"];
}
print_r($res);
Should result in:
Array
(
[ALFA] => 187
[BETA] => 167
[ZETA] => 254
[GAMA] => 175.5
)
Sample: http://phpfiddle.org/lite/code/a7nt-5svf
There are many nice Q&A on Stackoverflow on how to take a multidimensional associative array and sum values in it. Unfortunately, I can't find one where the key names aren't lost.
For example:
$arr=array(
array('id'=>'1', 'amount'=>'5'),
array('id'=>'1', 'amount'=>'5'),
array('id'=>'2', 'amount'=>'1'),
array('id'=>'2', 'amount'=>'3')
);
I want the resulting array to look like this:
$result=array(
array('id'=>'1', 'amount'=>'10'),
array('id'=>'2', 'amount'=>'4')
);
Unfortunately the only thing I can figure out how to do is this:
$result = array();
foreach($arr as $amount){
if(!array_key_exists($amount['id'], $arr))
$result[$amount['id']] =0;
$result[$amount['id']] += $amount['amount'];
}
Which when echo'd as follows produces (notice the lack of the keys' words "id" and "amount"):
foreach($result as $id => $amount){
echo $id."==>".$amount."\n";
}
1==>10
2==>4
This is just to show that you already had the data you originally needed, though, the answer you accepted is a better way to deal with it.
You have the following to start with right?
$arr = array(
array('id'=>'1', 'amount'=>'5'),
array('id'=>'1', 'amount'=>'5'),
array('id'=>'2', 'amount'=>'1'),
array('id'=>'2', 'amount'=>'3')
);
Output
Array
(
[0] => Array
(
[id] => 1
[amount] => 5
)
[1] => Array
(
[id] => 1
[amount] => 5
)
[2] => Array
(
[id] => 2
[amount] => 1
)
[3] => Array
(
[id] => 2
[amount] => 3
)
)
Then you run it through the following algorithm:
$summedArr = array();
foreach ($arr as $amount) {
$summedArr['amount'][$amount['id']] += $amount['amount'];
$summedArr['id'][$amount['id']] = $amount['id'];
}
Now, disregarding the Notice warnings that are produced since you are referencing indexes that don't yet exist, this outputs the following:
Output
Array
(
[amount] => Array
(
[1] => 10
[2] => 4
)
[id] => Array
(
[1] => 1
[2] => 2
)
)
Do you see the keys, yet? Because I do.
Now iterate over the array:
foreach ($summedArr as $key => $value) {
echo $k . "==>" . $v . "\n";
}
Output
amount==>Array
id==>Array
That's not what you want, though. You want:
foreach ($summedArr as $key => $arr) {
foreach ($arr as $v) {
echo $key . "==>" . $v;
}
}
Why not use that method, and then reconstruct the array you want at the end?
$results = array();
foreach ($arr as $id=>$amount) {
$results[] = array('id' => $id, 'amount' => $amount);
}
Any other way of doing this would be more computationally expensive.
foreach ($this->CsInventory as $value)
{
print_r($value) // print 1
$vname = $value[] = $value['VesselName'];
$total = $value[] = $value['Total'];
$Box = $value[] = $value['Box'];
print_r($value); // print 2
$rdata .= '<td>'.$vname.'</td>
<td>'.$total.'</td>
<td>'.$Box.'</td>';
}
Print 1
Array
(
[VesselName] => MARIANNE
[Total] => 13838
[Box] => 1156
)
Array
(
[Box] => 154
)
Array
(
[Box] => 3825
)
Array
(
[Box] => 50571
)
print 2
Array
(
[VesselName] => MARIANNE
[Total] => 15452
[Box] => 1156
[0] => MARIANNE
[1] => 15452
[2] => 1156
)
Array
(
[Box] => 2276
[0] =>
[1] =>
[2] => 2276
)
Array
(
[Box] => 3825
[0] =>
[1] =>
[2] => 3825
)
Array
(
[Box] => 49235
[0] =>
[1] =>
[2] => 49235
)
i how can i remove an empty value in the array? i try many ways but i can get any solution.. so decide to here in the forum?
I'd try to reduce effort.
foreach ($this->CsInventory as $value)
{
foreach ($value as $key => $item)
{
$value[] = $item;
$rdata .= "<td>$item</td>";
}
print_r($value)
}
As a general comment, not sure why you're adding anonomous values back to the $values stack, might be better to use a different array.
If you have specific array elements you want to get rid of, you can use unset($array[$key]);
You could also prevent them getting into the array in the first place by using
if($value['VesselName']) {$vname = $value[] = $value['VesselName'];}
instead of simply
$vname = $value[] = $value['VesselName'];
function array_remove_empty($arr){
$narr = array();
while(list($key, $val) = each($arr)){
if (is_array($val)){
$val = array_remove_empty($val);
// does the result array contain anything?
if (count($val)!=0){
// yes :-)
$narr[$key] = $val;
}
}
else {
if (trim($val) != ""){
$narr[$key] = $val;
}
}
}
unset($arr);
return $narr;
}
array_remove_empty(array(1,2,3, '', array(), 4)) => returns array(1,2,3,4)