How to create add an array to a multidimensional array - php

I'm trying to merge an array into another. If a business is a child of it's sector.
My aim is to create a array that looks like this:
[0] => Array (
[sector] => 198
[business] => Array (
[0] => 201
)
)
[1] => Array (
[sector] => 178
[business] => Array (
[0] => 181
[1] => 182
)
)
I currently have this:
[0] => Array (
[sector] => 198
)
[1] => Array (
[sector] => 178
)
and this (business ids):
Array
(
[0] => 201
)
Array
(
[0] => 181
[1] => 182
)
I need to nest these under sector.
This is what I have at the moment
$targets = array();
foreach ($taxonomy['sector'] as $sectorKey=>$sector) {
$getSectorTerm = get_term_by('slug', $sector, 'sector');
$getSectorId = $getSectorTerm->term_id;
$targets[] = array('sector'=>$getSectorId, 'business'=>[]);
foreach ($taxonomy['business'] as $keyBusiness=>$businesses) {
foreach ($businesses as $key => $business) {
$getBusinessTerm = get_term_by('slug', $business, 'sector');
$getBusinessId = $getBusinessTerm->term_id;
$getParentTerm = get_term( $getBusinessTerm, 'sector' );
$businessParentId = $getParentTerm->parent;
if ($businessParentId == $getSectorId) {
array_push($targets, $getBusinessId);
}
}
}
}
print_r($targets);
die;
The output is
Array
(
[0] => Array
(
[sector] => 198
)
[1] => 201
[2] => Array
(
[sector] => 178
)
[3] => 181
[4] => 182
)
Any help would be much appreciated.
Thanks

It should be work like this:-
$targets = array();
foreach ($taxonomy['sector'] as $sectorKey=>$sector) {
$getSectorTerm = get_term_by('slug', $sector, 'sector');
$getSectorId = $getSectorTerm->term_id;
$target_array = array('sector'=>$getSectorId, 'business'=>[]);
foreach ($taxonomy['business'] as $keyBusiness=>$businesses) {
foreach ($businesses as $key => $business) {
$getBusinessTerm = get_term_by('slug', $business, 'sector');
$getBusinessId = $getBusinessTerm->term_id;
$getParentTerm = get_term( $getBusinessTerm, 'sector' );
$businessParentId = $getParentTerm->parent;
if ($businessParentId == $getSectorId) {
$target_array['business'][] = $getBusinessId;
}
}
}
$targets[] = $target_array;
}
print_r($targets);
die;

If you'll keep current structure of array, it would be hard to populate the array with subarrays. It requires additional loop through the aray to find a certain sector value.
Are you able to change array structure to make it more compact and accessible? I mean that compact array has keys equal to sectors ID, and values are array of business IDs. For example like this:
[198] => Array (
[0] => 201
)
[178] => Array (
[0] => 181
[1] => 182
)
$targets = array();
foreach ($taxonomy['sector'] as $sectorKey=>$sector) {
$getSectorTerm = get_term_by('slug', $sector, 'sector');
$getSectorId = $getSectorTerm->term_id;
$targets[ $getSectorId ] = [];
foreach ($taxonomy['business'] as $keyBusiness=>$businesses) {
foreach ($businesses as $key => $business) {
$getBusinessTerm = get_term_by('slug', $business, 'sector');
$getBusinessId = $getBusinessTerm->term_id;
$getParentTerm = get_term( $getBusinessTerm, 'sector' );
$businessParentId = $getParentTerm->parent;
if ($businessParentId == $getSectorId) {
$targets[ $getSectorId ][] = $getBusinessId;
}
}
}
}
print_r($targets);
die;
To get a table:
foreach($targets as $sector => $businesses) {
echo "Sector ID: $sector<br>";
foreach( $businesses as $business ) {
echo "Business ID: $business<br>";
}
}

Related

Php string comparision in multidimensional array

I have two multidimensional array
Array
(
[0] => Array
(
[code] => 2079
[label] => Nike
)
[1] => Array
(
[code] => 1080
[label] => Adidas
)
)
Array
(
[0] => Array
(
[manufacturers_id] => 2753
[manufacturers_name] => Reebok
)
[1] => Array
(
[manufacturers_id] => 2526
[manufacturers_name] => Adidas
)
[2] => Array
(
[manufacturers_id] => 34
[manufacturers_name] => Nike
)
)
I want to do string matching of a key label of array 1 with key manufacturer_name of array 2. What is the best approach in multidimensional arrays ?
You could loop trough the arrays.
foreach ($multi_array1 as $value) {
foreach ($multi_array2 as $value2) {
If ($value[label] === $value2 [manufacturer_name])
{}
}
}
If you want to match by label and manufacturers_name, then I suggest you reindex your arrays by those fields:
$by_label = [];
foreach($first_array as $element) {
$by_label[$element['label']] = $element['code'];
}
$by_name = [];
foreach($second_array as $element) {
$by_label[$element['manufacturers_name']] = $element['manufacturers_id'];
}
foreach($by_label as $label => $code) {
print "Label is $label, code is $code, id is {$by_name[$label]}";
}
foreach($by_name as $name => $id) {
print "Name is $name, id is $id, label is {$by_label[$name]}";
}
Just use foreach to accomplish your desire result.
Array
$firstArr = array(
array("code" => 2079, "label" => 'Nike'),
array("code" => 1080, "label" => 'Adidas')
);
$secArr = array(
array("manufacturers_id" => 2753, "manufacturers_name" => 'Reebok'),
array("manufacturers_id" => 2526, "manufacturers_name" => 'Adidas'),
array("manufacturers_id" => 34, "manufacturers_name" => 'Nike')
);
Foreach Technique:
foreach($firstArr as $value){
if(in_array_sec($value['label'])){
echo $value['label'].' found in second array.';
}else{
echo $value['label'].' not found in second array.';
}
}
function in_array_sec($val_one){
global $secArr;
$flag = false;
foreach($secArr as $value){
if($value['manufacturers_name'] == $val_one){
$flag = true;
break;
}
else
$flag = false;
}
return $flag;
}
Result:
Nike found in second array.
Adidas found in second array.

group php array by subarray value

I want to group an array by a subarray's value. If I have an array like this:
Array
(
[0] => Array
(
[userID] => 591407753
[propertyA] => 'text1'
[propertyB] => 205
)
[1] => Array
(
[userID] => 989201004
[propertyA] =>'text2'
[propertyB] => 1407
)
[2] => Array
(
[userID] => 989201004
[propertyA] => 'text3'
[propertyB] => 1407
)
)
I want to sort to group this array by a subarray's value so I can have an array like this:
Array
(
[0]=>Array
(
[userID]=>59140775
[properties]=>Array
(
[0]=>text1
)
[propertyB]=>205
)
[1]=>Array
(
[userID]=>989201004
[properties]=>Array
(
[0]=>'text2'
[1]=>'text3'
)
[propertyB]=>1047
)
)
How can I make this?
Before I had tried this:
$result = array();
foreach ($userArray as $record)
{
$id=$record['userID'];
if(isset($result[$id]))
{
$result[$id]['propertyA'][]=array($record['propertyA']);
}
else {
$record["propertyA"]=array($record['propertyA']);
unset($record['tweet']);
$result[$id]=$record;
}
}
the problem was for the propertyA. I was an the result an additional property propertyA with the table like this:
Array
(
[0]=>Array (
[userID]=>989201004
[propertyA]=>'text2'
[properties]=>Array(
[0]=>'text2'
[1]=>'text3'
)
)
)
The following code should do the job. I hope it is self-explanatory:
$result = array();
foreach ($array as $record) {
if (!isset($result[$record['userID']])) {
$result[$record['userID']] = array(
'userID' => $record['userID'],
'properties' => array($record['propertyA']),
'propertyB' => $record['propertyB'],
);
}
else {
$result[$record['userID']]['properties'][] = $record['propertyA'];
}
}
$result = array_values($result);

How to build custom array in multi level foreach?

Here is the raw data
Array
(
[name] => me
[tickets] => Array
(
[1] => Array
(
[equipment] => Array
(
[1] => Array
(
[name] => DVR
[received] => 10
)
[2] => Array
(
[name] => DCT
[received] => 3
)
)
)
[2] => Array
(
[equipment] => Array
(
[1] => Array
(
[name] => DVR
[received] => 4
)
[2] => Array
(
[name] => DCT
[received] => 6
)
)
)
)
)
Users have multiple tickets, but each ticket has the same item with different 'received' amounts. I would like to sum the received amount into one variable/array.
Here is a demo of how I would like to get it to work like
Array
(
[name] => me
[equipment] => Array
(
[DVR] => 14
[DCT] => 9
)
)
Here is my most recent failed attempt at building my own array from a multidimensional array.
foreach($data as $user){
$sum = [];
$sum['name'] = $user->name;
$sum['equipment'] = [];
foreach($user->tickets as $ticket){
foreach($ticket->equipments as $eqpt){
$sum['equipment'][$eqpt['name']] += $eqpt['pivot']['received'];
}
}
print_r($sum);
}
Please try the following code. There's only a single user in your $data, though, so you need to do $data = [$data]; first.
foreach ($data as $user) {
$sum = [];
$sum['name'] = $user['name'];
$sum['equipment'] = [];
foreach($user['tickets'] as $ticket){
foreach($ticket['equipment'] as $eqpt){
$sum['equipment'][$eqpt['name']] += $eqpt['received'];
}
}
print_r($sum);
}
PHP arrays are accessed with square bracket syntax
There's probably a typo in $ticket->equipments.
Try with this:
$array = $data; //$data is your array
$sum = array('name' => $array['name'], 'equipment' => array());
foreach($array['tickets'] as $row) {
for($i = 0; $i < count($row); $i++) {
foreach($row['equipment'] as $infos) {
$sum['equipment'][$infos['name']] += $infos['received'];
//print_r($infos);
}
}
}
print_r($sum);
well, after much googling and trial and error this appears to work
$sum = [];
// $data is a collection returned by Laravel
// I am converting it to an array
foreach($data->toArray() as $user){
$items = [];
foreach($user['tickets'] as $ticket){
foreach($ticket['equipments'] as $eqpt){
$name = $eqpt['name'];
if (! isset($items[$name]))
{
$items[$name] = $eqpt['received'];
} else {
$items[$name] += $eqpt['received'];
}
}
}
$sum[] = [
'name' => $user['name'],
'equipment' => $items
];
}
#tsnorri #Adrian Cid Almaguer

Merge multidimensional arrays in PHP

I would like create a list of values within a new array based on the same keys from the previous array. Basically, I would like to turn this array:
$old_array = Array (
[segment1] => Array (
[subsegment] => Array (
[number1] => 1413
[number2] => 306
)
)
[segment2] => Array (
[subsegment] => Array (
[number1] => 717
[number2] => 291
)
)
)
...into this array:
$new_array = Array (
[segment] => Array (
[subsegment] => Array (
[number1] => Array (
[0] => 1413
[1] => 717
)
[number2] => Array (
[0] => 306
[1] => 291
)
)
)
)
I tried the following:
$new_array = array ();
foreach ($old_array["segment"]["subsegment"] as $value) {
$new_array["segment"]["subsegment"][] = $value;
}
Unfortunately, this doesn't work. What do I need to do? Thanks.
This is very specific to your example $old_array:
$index = 1;
$new_array = array();
do {
if (!isset($old_array["segment" . $index]["subsegment"]))
break;
foreach ($old_array["segment" . $index]["subsegment"] as $key => $value) {
$new_array["segment"]["subsegment"][$key][] = $value;
}
$index++;
} while (true);
I understand you want all number1's in the same key, then all number 2's, and so on. try this:
$numberCount = count($old_array['segment1']['subsegment']);
foreach ($old_array as $segment)
{for ($i=1;$i<=$numberCount;$i++)
{$new_array['segment']['subsegment']['number' . $i][] = $segment['subsegment']['number' . $i];}}
this is assuming all subsegment have the same number of [numberx] keys

Is it possible to group this array?

I have an array and I need to sort this array in a multilevel array. I'm trying to group it by its fields but I can make it work. Here is the example of the array I have and what I want
Array
(
[0] => Array
(
[id] => sports
[title] => this is sports
)
[1] => Array
(
[id] => cricket
[title] => this is cricket
[under] => sports
)
[2] => Array
(
[id] => batsman
[title] => this is batsman
[under] => cricket
)
[3] => Array
(
[id] => sachin
[title] => this is sachin
[under] => batsman
)
[4] => Array
(
[id] => football
[title] => this is football
[under] => sports
)
[5] => Array
(
[id] => ronaldo
[title] => this is ronaldo
[under] => football
)
)
I need to group this array and make it like this
Array(
[0] => Array(
[id] => Array(
[sports] => Array(
[cricket] => Array(
[batsman] => sachin
)
[football] => fun
)
)
)
)
I tried something like this but it is not working
foreach($my_array as $item) {
//group them by under
$my_grouped_array[$item['under']][] = $item;
}
Any suggestion will be great.
I think this is the most straight-forward way of doing this:
function getChildren($entry,$by_parent){
$children = array();
if (isset($by_parent[$entry['id']])){
foreach ($by_parent[$entry['id']] as $child){
$id = $child['id'];
$children[$id] = getChildren($child,$by_parent);
}
}
return $children;
}
$by_parent = array();
$roots = array();
foreach ($array as $entry){
if (isset($entry['under'])){
$by_parent[$entry['under']][] = $entry;
} else {
$roots[] = $entry;
}
}
$result = array();
foreach ($roots as $entry){
$id = $entry['id'];
$result[$id] = getChildren($entry,$by_parent);
}
$results = array(array('id'=>$results));
NOTE: This isn't quite the format specified in the question, but the question doesn't define how to deal with multiple leaf nodes with the same parent, and this should be easier to traverse anyway, because it's more consistent.
I wrote a recursive function that does what you want, but bare in mind that if you have more than one last element of a branch only the first one will be saved.
Here's the function:
function rearrange(&$result, $my_array, $element = NULL)
{
$found = 0;
$childs = 0;
foreach($my_array as $one) if(#$one['under'] == $element)
{
$found++;
if( ! is_array($result)) $result = array();
$result[$one['id']] = $one['id'];
$childs += rearrange($result[$one['id']], $my_array, $one['id']);
}
if( ! $childs AND is_array($result))
$result = reset($result);
return $found;
}
You can call it like that:
$result = array(array('id' => array()));
rearrange($result[0]['id'], $my_array);
print_r($result);
Use php object:
function populateArray($my_array) {
//Populate the array
while ($my_array as $item) {
$array[$item->id]['id'] = $obj->id;
$array[$item->id]['name'] = $obj->name;
}
return $array;
}
$a = populateArray($array);
echo $a[0]['id'].'<br />';
echo $a[0]['name'].'<br />';
or use new foreach

Categories