PHP Multidimensional Associative Array - how to get list of keys? - php

Here is an example of my data:
[204] => Array
(
[1] => Array
(
[leads] => 9
)
[2] => Array
(
[leads] => 15
)
)
[200] => Array
(
[1] => Array
(
[leads] => 7
)
[2] => Array
(
[leads] => 16
)
[3] => Array
(
[leads] => 5
)
)
I am at the stage where I trying to output the array data into a table but how do I set up the table headers dynamically so that the columns will be 1 | 2 | 3, even if some subsets don't have an array of that type?
The array is constructed from the results of a database query like so:
$dailytotals[$store][$campaigntypeid] = array('leads'=> $leads);
I tried a for each but just realised that it wouldn't work since not all subsets have all columns.
Is there a way to get what I am trying to find?

Try this
$columns = array();
foreach ($your_array as $key=> $arr) {
$columns = array_unique(array_merge($columns, array_keys($arr)));
}
Another way
$columns = array_reduce($your_array,
function ($r, $val) {
return array_unique(array_merge($r, array_keys($val)));
},
array()
);

Related

Convert comma separated array to nested array with php function

I need to convert array_1 to array_2 with a PHP function. I tried many things but nothing works. I hope someone can help me out here. I think I need an each function or something to loop through the comma separated array and convert it into the array_2.
$array_1 = array (
0 => '6801,6800,7310,6795',
);
$array_2 = array (
0 =>
array (
0 => '6801',
1 => '6800',
2 => '7310',
3 => '6795',
),
);
Here a solution
<?php
$array_1 = array (
0 => '6801,6800,7310,6795',
);
$array_2 = array();
foreach ($array_1 as $value) {
array_push($array_2 , explode(",",$value));
}
print_r($array_2);
?>
The output that i got
Array ( [0] => Array ( [0] => 6801 [1] => 6800 [2] => 7310 [3] => 6795 ) )
Use PHP explode function. https://www.php.net/manual/de/function.explode.php
$newArray[] = explode(",", $array_1[0]);
// output
Array
(
[0] => Array
(
[0] => 6801
[1] => 6800
[2] => 7310
[3] => 6795
)
)
Just create a new array with a value returned by the explode function. Reset always returns the first value of the array regardless of the key.
$array_1 = array (0 => '6801,6800,7310,6795');
$newArray = [explode(",", reset($array_1))];

How to update an Associative Array

I do not know what is wrong with my php code. I want to have an Associative Array in the format. When I run my code I get this data. [KY] is an array in the [OH] array.
Array ( [Oh] => Array ( [state] => Oh ) [income] => 100 [count] => 1 [Ky] => Array ( [state] => Ky ) )
Array (
[OH] => Array
( [income] =>
[count] =>
)
[KY] => Array
( [income] =>
[count] =>
)
Here is my code
Example data in $array
Array ( [0] => Array (
[SurveyDate] => 1952-06-21
[Income] => 100
[CountyState] => Hamilton|Oh
[count] => 1 ) )
function update_array_value3( $array )
{
foreach ($array as $row)
{
$arrCountyState = explode( "|", $row['CountyState'] );
$key = $arrCountyState[1]; // OH or KY
if( !isset( $_SESSION['sIncome'][$key] ) )
{
$_SESSION['sIncome'][$key]['state'] = $key;
$_SESSION['sIncome'][$key]['income'] = $row['Income'];
$_SESSION['sIncome'][$key]['count'] = 1;
} else
{
$_SESSION['sIncome'][$key]['state'] = $key;
$_SESSION['sIncome'][$key]['income'] += $row['Income'];
$_SESSION['sIncome'][$key]['count'] += 1;
}
}
I can't tell you the root cause of the problem simply based on this snippet of code, but it seems $row either doesn't contain the data you expect it to, or doesn't contain any data.
In your code you reference $row['CountyState'], yet I don't see any array item called CountyState in $array.
Also, I'm not sure whether or not this is intentional, but in your foreach() loop it looks like $_SESSION['sIncome']['income'] and $_SESSION['sIncome']['count'] are being overwritten. Each time the loop encounters a new $key, it will overwrite those values.

how to search in array to find all sub arrays that contain a certain value

i have a array placed in the variable $class that is constituted of sub arrays containing 2 student id's each,
i am trying to find all the sub arrays that contain a certain id for example 11
i want to keep all arrays containing this id in a variable.
array example
Array
(
[0] => Array
(
[s1] => 6
[s2] => 37
)
[1] => Array
(
[s1] => 8
[s2] => 11
)
[2] => Array
(
[s1] => 11
[s2] => 48
)
)
code
foreach ($class as $key => $value) {
if(!in_array($id, $class)){
unset($class[$key]);
}
}
You are close. If you loop and reference the correct variable with the in_array(), it would work as you hopefully need. Then assign the matching array into a new array var to use later (so you are not altering your original array!):
$id = 11;
$matched = array();
foreach ($class as $i => $students) {
if ( in_array($id, $students) ) {
$matched[] = $class[$i];
}
}
print_r($matched);
Would result in:
Array (
[0] => Array
(
[s1] => 8
[s2] => 11
)
[1] => Array
(
[s1] => 11
[s2] => 48
)
)
Associative array
http://php.net/manual/es/function.array-search.php
$class = array(array("s1"=>6, "s2"=>37),array("s1"=>8,"s2"=>11),array("s1"=>11, "s2"=>48));
$id = 11;
foreach ($class as $key => $value) {
if(!array_search($id, $value)){
unset($class[$key]);
}
}
Sorry, you can follow this answers
using array_search for multi dimensional array

How to iterate over a multidimensional array?

I have array like this. This array is created dynamically
Array
(
[Data NotUploading] => Array
(
[items] => Array
(
[0] => Array
(
[date] => 2013-04-02
[issue_id] => 1
[phone_service_device] => A
[phone_service_model] =>
[phone_service_os] =>
[phone_service_version] =>
[issue_name] => Data NotUploading
)
[1] => Array
(
[date] => 2013-04-02
[issue_id] => 1
[phone_service_device] => I
[phone_service_model] =>
[phone_service_os] =>
[phone_service_version] =>
[issue_name] => Data NotUploading
)
)
)
[Battery Problem] => Array
(
[items] => Array
(
[0] => Array
(
[date] => 2013-04-03
[issue_id] => 3
[phone_service_device] => I
[phone_service_model] =>
[phone_service_os] =>
[phone_service_version] =>
[issue_name] => Battery Problem
)
)
)
)
What I need to do is to use 2 foreach or 1 foreach & 1 for loop so that I can get each value of date I did like this
foreach($gResultbyName as $key1 => $rec){
for($j = 0;$j<count($rec);$j++ ){
echo $rec['items'][$j]['date'];
}
}
but its only retrieving 2013-04-02 & 2013-04-03 that is 0 index date of data NotUploading & 0 index date of Battery Problem. Basically I need to compare each value and others stuff but I just cant get each date value.
Forgive me for ignorance but I tried a lot :(
try this:
foreach ($data as $d)
{
foreach($d['items'] as $item)
{
echo $item['date'];
}
}
Your for-loop loops count($rec) times, but should count($rec['items']).
This should load the dates into an array sorted by the issue_name. The you can step through them for further processing.
$dates= array();
foreach ($gResultbyName AS $events){
foreach ($events['items'] AS $item){
$dates[$item['issue_name']][] = $item['date'];
}
}
var_dump($dates);

Problem with Building Arrays in Different Coding Styles

I'm having a strange problem while building arrays. I start off with an array that looks like this:
Array (
[0] => Array (
[tag_id] => 19
[tag_translation_id] => 12
[fk_language_id] => 1
[fk_tag_id] => 19
[tag_name] => test
)
[1] => Array (
[tag_id] => 20
[tag_translation_id] => 14
[fk_language_id] => 1
[fk_tag_id] => 20
[tag_name] => testa
)
[2] => Array (
[tag_id] => 20
[tag_translation_id] => 15
[fk_language_id] => 3
[fk_tag_id] => 20
[tag_name] => fdfda
)
)
What I want to do is merge each result with the same tag_id into a single array. This works:
$tags = array();
foreach($results->as_array() as $key=>$result)
{
if(!in_array($result['tag_id'], $tags))
{
$tags[$result['tag_id']] = array();
}
}
foreach($results->as_array() as $result)
{
array_push($tags[$result['tag_id']], array($result['fk_language_id'] , $result['tag_name']));
}
Here is the intended result:
Array (
[19] => Array (
[0] => Array (
[0] => 1
[1] => test
)
)
[20] => Array (
[0] => Array (
[0] => 1
[1] => testa
)
[1] => Array (
[0] => 3
[1] => fdfda
)
)
)
However, I've got two loops here, and I know this isn't ideal. Why do THESE not work??
$tags = array();
foreach($results->as_array() as $key=>$result)
{
$tags[$result['tag_id']] .= array($result['fk_language_id'] , $result['tag_name']);
}
With this example I get two empty arrays...
Array ( [19] => Array [20] => ArrayArray )
Or even...
$tags = array();
foreach($results->as_array() as $key=>$result)
{
if(!in_array($result['tag_id'], $tags))
{
$tags[$result['tag_id']] = array();
}
array_push($tags[$result['tag_id']], array($result['fk_language_id'] , $result['tag_name']));
}
Which for some reason overwrites the first value of the second array with the second value of the second array.
Array (
[19] => Array (
[0] => Array (
[0] => 1
[1] => test
)
)
[20] => Array (
[0] => Array (
[0] => 3
[1] => fdfda
)
)
)
What am I doing wrong in the second 2 examples?
To answer your question, your second method fails because you're using the incorrect .= operator. Your third method fails because your !in_array check is always false (it checks whether the value is in the array, not whether the key is set) and overwrites the array each iteration. You only really need this (as mentioned by others, in pseudo-code):
$result = array();
foreach ($array as $values) {
$result[$values['key']][] = array($values['foo'], $values['bar']);
}
The .= operator is string concatenation. Arrays are merged with +=.
If I understand the issue correctly, the code should go like this:
$tags = array();
foreach ($results as $result)
$tags[$result['tag_id']][] = array($result['fk_language_id'], $result['tag_name']);
$tags = array();
foreach($results->as_array() as $key=>$result)
{
$tags[$result['tag_id']] .= array($result['fk_language_id'] , $result['tag_name']);
}
you cannot add a value to an array with the .= (dot equal) operator.
why are you doing $results->as_array() ????
do simply:
foreach($results as $key=>$result) {
Instead of using .= try using []
$tags = array();
foreach ($results as $result)
{
if(!isset($tags[$result['tag_id']]))
$tags[$result['tag_id']] = array();
$tags[$result['tag_id']][] = array($result['fk_language_id'], result['tag_name']);
}
.= is to concatinate a string
+= is to concatinate a number
[] is to concatinate to an array
Hope this helps?
Edit: Noticed that it "might" fail if the tag_id doesn't already exist in the array, so it might be worth just checking first and setting it to an array just in case.

Categories