How to create this multidimensional array in PHP - php

I want to fill an array in a while loop.
I want to display this array like this :
category 1 => Company A => 'name', 'city', 'CEO',
Company B => 'name', 'city', 'CEO'
category 2 = Company A => 'name', 'city', 'CEO',
Company B => 'name', 'city', 'CEO'
ect ........
Here's my current code in my while loop
$array_cat[] = array(
array(
'category' => $cat,
array(
'company' => array(
'name' => $name,
'city' => $city,
'CEO' => $ceo
)
)
)
);
My code WHen I display it
foreach ($array_cat as $item) {
foreach ($array_cat['category'] as $company_display) {
echo $company_display['company']['name'][];
}
}
Thanks for the help ;)

try this:
$array1 = array('category1' =>
array('Company A' =>
array('name', 'city', 'CEO')),
'category2' =>
array('Company B' =>
array('name', 'city', 'CEO')));
foreach ($array1 as $key => $value)
{
foreach ($value as $key1 => $value1)
{
echo "<pre>";
print_r($value1);
echo "</pre>";
}
}
Problem is in your inner foreach loop

There is a problem in inner foreach loop and echo line.
Replace $array_cat by $item and in echo line there is an error:
Cannot use [ ] for reading
By following way, you can achieve your goal.
foreach ($array_cat as $item) {
foreach ($item as $company_display) {
echo $company_display['category']['company']['name'];
}
}

How to create this multidimensional array in PHP
If I would design an array for that, i would do something like this:
$array = array(
//Category 1, nameless i assume?
array(
//Companies
"Company A" => array(
//Company properties
"name" => "My A company",
"city" => "Some city that starts with an A",
"CEO" => "Some CEO that starts with an A"
),
"Company B" => array(
//Company properties
"name" => "My B company",
"city" => "Some city that starts with an B",
"CEO" => "Some CEO that starts with an B"
),
),
//Category two, nameless i assume
array(
//Companies
"Company C" => array(
//Company properties
"name" => "My C company",
"city" => "Some city that starts with an C",
"CEO" => "Some CEO that starts with an C"
),
"Company D" => array(
//Company properties
"name" => "My D company",
"city" => "Some city that starts with an D",
"CEO" => "Some CEO that starts with an D"
),
),
);
Then, if i wanted to get some data out of it, i could do something like this:
$companyAcity = $array[0]['Company A']['city'];
echo $companyAcity;
If I wanted to loop in the array, i could so something like this:
for($categoryID = 0; categoryID < count($array); $i++) {
//Prints data for each category it loops through.
echo $array[$categoryID];
//Loops through the companies contained in the current category where it's looping through
foreach($array[$categoryID] as $companyName => $companyData) {
echo $companyName;
echo $companyData['name'];
}
}
I want to fill an array in a while loop.
If you want to add data to the array while looping in it, you can do something like this:
for($categoryID = 0; categoryID < count($array); $i++) {
$array[$categoryID][] = $categoryID +1;
}

Related

Remove from multidimensional array if has seen id before in an basic array

I would like in php to stop duplicate messages by logging msgid to a text file using something like this file_put_contents("a.txt", implode(PHP_EOL, $array1), FILE_APPEND);
and then converting it back to an array using $array1 = file("a.txt"); I would also like to delete messages from the array if they are from a set name
I know how to convert json to an array $array1 = json_decode($json, true);
Json Reply from an api that I cannot control
{
"API": "Online",
"MSG": [
{
"info": {
"name": "example"
},
"msg": "example",
"msgid": "example"
},
{
"info": {
"name": "example"
},
"msg": "example",
"msgid": "example"
}
]
}
Hi use the following code, first test it out accordingly
$uniqueMessages = unique_multidim_array($messages,'msg');
Usage : Pass the key as the 2nd parameter for which you need to check the uniqueness of array.
<?php
/* Function to handle unique assocative array */
function unique_multidim_array($array, $key) {
/* temp array to hold unique array */
$temp_array = array();
/* array to hold */
$i = 0;
/* array to hold the key for unique array */
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
$messages = array(
0 => array(
'info' => array(
'name' => 'example'
),
'msg' => 'example',
'msgid' => 'example'
),
1 => array(
'info' => array(
'name' => 'example 1'
),
'msg' => 'example 1',
'msgid' => 'example 1'
),
3 => array(
'info' => array(
'name' => 'example'
),
'msg' => 'example',
'msgid' => 'example'
)
);
echo '<pre>';
echo '*****************BEFORE***********************<br/>';
var_dump($messages);
echo '*****************AFTER***********************<br/>';
$uniqueMessages = unique_multidim_array($messages,'msg');
var_dump($uniqueMessages);
This works for me this is an modded function click here for original function
function RemoveElementByArray($array, $key, $seen){
foreach($array as $subKey => $subArray){
if(in_array($subArray[$key], $seen)){
unset($array[$subKey]);
}
}
return $array;
}
Example:
$array = array(
array("id" => "1", "name" => "example1"),
array("id" => "2", "name" => "example2"),
array("id" => "3", "name" => "example3"));
$SeenArray = array("1", "2");
print_r(RemoveElementByArray($array, "id", $SeenArray));
Result:
Array
(
[2] => Array
(
[id] => 3
[name] => example3
)
)

PHP array_intersect / array_diff / combine array

$arr[] = array('title' => 'Overview');
$arr[] =array('title' => 'General');
$arr[] =array('title' => 'History');
$arr[] =array('title' => 'Construction');
$arr[] =array('title' => 'Plan');
$arr[] =array('title' => 'Other');
$info_arr[] = array("title" => "General", text => "value1");
$info_arr[] = array("title" => "History", text => "value1");
$info_arr[] = array("title" => "Construction", text => "value1");
$info_arr[] = array("title" => "Plan", text => "value1");
I need to be able merge these arrays together.So they look something like this. As I will need to loop thru the consolidated array. Other, Overview do not have any text values but still need to placed into the array.
$new_arr[] = array("title" => "General", text => "value1", "title" => "History", text => "value1", "title" => "Construction", text => "value1"
,"title" => "Plan", text => "value1","title" => "Overview", text => "","title" => "Other", text => "");
I have tried for loops (using count value), foreach loops, I thought array_intersect or array_diff don't see to solve the issue. This should not be so difficult, but I'm trying to piece together some really bad legacy code. Or the cube/florescent lights might have finally got to me.
Update:
while ($stmt->fetch()) {
$arr[] = array("title" => $Title);
}
and
while ($dstmt->fetch()) {
$info_arr[] = array("title" => $descriptionType, "descriptiontext" => $descriptionText); , "descriptiontext" => $val );
}
$dstmt & $stmt are queries.
I thought this would work but not so much
$r = array_intersect($arr, $info_arr);
var_dump($r);
Something like this Let me clarify:
$new_arr = array(array("title" => "General", text => "value1"),
array("title" => "History", text => "value1"),
array("title" => "Construction", text => "value1"),
array("title" => "Plan", text => "value1"),
array("title" => "Overview", text => ""),
array("title" => "Other", text => "")
);
If you want to work with these two arrays, you can just use the title as the key in $r.
foreach (array_merge($arr, $info_arr) as $x) {
$r[$x['title']]['title'] = $x['title'];
$r[$x['title']]['text'] = isset($x['text']) ? $x['text'] : '';
}
Or, you can go back a step and avoid having separate arrays by building the $r array in the same manner as you fetch your query results:
while ($stmt->fetch()) {
$r[$Title] = array('title' => $Title, 'text' => '');
}
while ($dstmt->fetch()) {
$r[$descriptionType] = array("title" => $descriptionType, "text" => $descriptionText);
}
Or, ideally, you could go back another step and avoid having separate queries by using a JOIN to get the same results in one query, but there's nothing in the question on which to base any specific suggestion for that.
As stated in the comments, the exact $new_arr you're requesting isn't possible. However, I think this will give you a similar result that should work for your purposes:
foreach ($info_arr as $infoArray) {
$found = array_search(array('title' => $infoArray['title']), $arr);
if (false !== false) {
unset($arr[$found]);
}
}
$new_arr = array_merge($info_arr, $arr);
It works by removing the "duplicates" from the original $arr before doing the array_merge().
If it's important to add an empty text value for the remaining items in $arr, do this before the array_merge():
foreach ($arr as &$arrArray) {
$arrArray['text'] = '';
}
The resulting array will look like this:
$new_arr[] = array(
array(
'title' => 'General',
'text' => 'value1',
),
array(
'title' => 'History',
'text' => 'value1',
),
array(
'title' => 'Construction',
'text' => 'value1',
),
array(
'title' => 'Plan',
'text' => 'value1',
),
array(
'title' => 'Overview',
'text' => '',
),
array(
'title' => 'Other',
'text' => '',
),
);

Appending an array to a multi dimensional array fails silently PHP?

I am trying to append an array to another one in a multi dimensional array:
This is the multi dimensional array:
$info[] = array(
'key' => $row['id'],
'master' => array(
'name' => $row['master_name'],
"detail" => array()
)
);
I has a key which is the master id, and a master item which is an array with a name and another array with the detail (at the first time is empty).
But when I try to add to the $info['master']['detail'] array another array with a detail, like this:
$info['master']['detail'][] = array("name" => "A detail name",
"value" => "A detail value");
Nothing is added... How is that possible?
EDIT: the foreach loops that should add the details to the master:
foreach ($details as $detail)
{
$name = $detail['detail_name'];
$value = $detail['detail_value'];
if ($info['key'] == $detail['id']) {
$info['master']['detail'][] = array("name" => $name,
"value" => $value);
}
}
I'm not sure I understand but when I see your examples, I think it is a problem of index:
Try to replace
$info[] = array(
'key' => $row['id'],
'master' => array(
'name' => $row['master_name'],
"detail" => array()
)
);
$info['master']['detail'][] = array("name" => "A detail name",
"value" => "A detail value");
by
$info = array( 'key' => $row['id'],
'master' => array('name' => $row['master_name'],,
"detail" => array())
);
$info['master']['detail'] = array("name" => "A detail name",
"value" => "A detail value");
and to add a new value :
$info['master']['detail']['foo'] = "A detail foo";

get all combination key codes from 2D array

I want to get the combination keys for an array - here the example:
$keys = array(
array(
'original',
'section 1',
'section 2'
),
array(
'original',
'section 1'
),
array(
'original',
'section 1'
),
array(
'original',
'section 1',
'section 2'
),
array(
'original',
'section 1'
)
);
all original sections would be 00000 (5 digits because of 5 different arrays, but there can be 1 to n arrays, not limited to 5) and variation #15 would be for example 01010. i basically want to get a list of all variations in a list with that key to get them. we assume that there are not more than 9 sections + original inside each array.
output should look like this:
array(
array(
"key" => "00000",
"data" => array(
"original", "original", "original", "original", "original"
)
),
array(
"key" => "10000",
"data" => array(
"section 1", "original", "original", "original", "original"
)
),
array(
"key" => "20000",
"data" => array(
"section 2", "original", "original", "original", "original"
)
),
array(
"key" => "01000",
"data" => array(
"original", "section 1", "original", "original", "original"
)
)
[...]
)
in addition to this it would be nice to have a good way to get it the other way too. giving the key 01010 and getting all sections back.
thanks!
Here is what i came up with:
$options = array();
$counter1 = 0;
foreach($keys as $values) {
$counter1++;
$counter2 = 0;
$options[$counter1] = array();
foreach($values as $key => $value) {
if(isset($options[($counter1 - 1)])) {
foreach($options[($counter1 - 1)] as $old_val) {
$counter2++;
$old_array = $old_val['data'];
array_push($old_array, $value);
$options[$counter1][$counter2] = array();
$options[$counter1][$counter2]['key'] = $old_val['key'] . $key;
$options[$counter1][$counter2]['data'] = $old_array;
}
}
else {
$counter2++;
$options[$counter1][$counter2] = array();
$options[$counter1][$counter2]['key'] = $key;
$options[$counter1][$counter2]['data'] = array($value);
}
}
}
$all_options = end($options);
You get 72 results which is correct because it is 3 * 2 * 2 * 3 * 2 = 72

Put nested array into one array

Suppose i have a array like this :
Array(
'1' => Array(
"ID" => 1,
"Name" => "name 1"
),
'2' => Array (
Array(
"ID" => 2,
"Name" => "name 2"
)
),
'3' => Array(
Array(
Array(
Array(
"ID" => 3,
"Name" => "name3"
)
)
),
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
number of sub-arrays is not ordered it may be 3, 4 or 5 etc...
and i wanted to get :
Array(
Array( "ID" => 1, "Name" => "name 1"),
Array( "ID" => 2, "Name" => "name 2"),
Array( "ID" => 3, "Name" => "name 3"),
Array( "ID" => 4, "Name" => "name 4"),
Array( "ID" => 5, "Name" => "name 5"),
Array( "ID" => 6, "Name" => "name 6"));
Is there an easy way to do this ?
EDIT :
Edited the above array to add :
'4' => Array (
Array {
"ID" => 4,
"Name" => "name 4"
),
Array(
"ID" => 5,
"Name" => "name 5"
),
Array(
"ID" => 6,
"Name" => "name 6"
)
);
which aren't nested but i still want them to be in my final array.
Thanks.
//Assuming your data is in $in
$out=array();
foreach($in as $k=>$v) {
while ((is_array($v)) && (isset($v[0]))) $v=$v[0];
//See below for next line
$out[]=$v;
}
print_r($out);
With the marked line being either $out[$k]=$v; or $out[]=$v; depending on wether you want to keep the 1st-level keys. In your desired output you do not ,so use the shown version
Edit
With you changed input array, you need to do something like
function addtoarray($inarray, &$outarray) {
foreach ($inarray as $i) {
if (!is_array($i)) continue;
if (isset($i['ID'])) $outarray[]=$i;
else addtoarray($i,$outarray);
}
}
$out=array();
addtoarray($in,$out);
print_r($out);
This was tested against your new input data
You could recurse through the array and check for the ID field.
function combine_array(array $src, array &$dest)
{
if( isset( $src['ID'] ) ) {
$dest[] = $src;
return;
}
foreach( $sub in $src ) {
combine_array( $sub, $dest );
}
}
Just wrote this off the top of my head, no testing, so it might have a few problems. But that's the basic idea.
This may work for you, assuming $array is the variable and php 5.3
//process
$array = array_map(function($block) {
$return = '';
foreach ($block as $sub) {
if (true === isset($sub['ID']) {
$return = $block;
break;
}
}
return $block;
}, $array);
array_filter($array); //remove empty elements
Wrote up a quick recursive function. You'll need to write any appropriate error handling and check the logic, since a discrepancy in your data could easily turn this into an infinite loop:
$output = array();
foreach ( $data as $d ) {
$output[] = loop_data( $d );
}
function loop_data( $data ) {
// Check if this is the right array
if( ! array_key_exists( "ID", $data ) ) {
// Go deeper
$data = loop_data( $data[0] );
}
return $data;
}

Categories