I have an array which looks like this:
array (
'id' => 1,
'channel_id' => 1,
'field_group' => 1,
'url_title' => 'the_very_first_entry',
'title' => 'The Very First Entry',
'fields' =>
array (
0 =>
array (
'label' => 'Enter Item Name:',
'type' => 'text',
'channel_data_id' => 1,
'value' => 'Item one',
'field_id' => 1
),
1 =>
array (
'label' => 'Enter Item Description',
'type' => 'textarea',
'channel_data_id' => 2,
'value' => 'Some long text blah blah',
'field_id' => 2
)
)
)
I want to split this into 2 arrays, one containing the fields, and the other containing everything else, ie.
Array 1:
array (
'id' => 1,
'channel_id' => 1,
'field_group' => 1,
'url_title' => 'the_very_first_entry',
'title' => 'The Very First Entry'
);
Array 2:
array (
0 =>
array (
'label' => 'Enter Item Name:',
'type' => 'text',
'channel_data_id' => 1,
'value' => 'Item one',
'field_id' => 1
),
1 =>
array (
'label' => 'Enter Item Description',
'type' => 'textarea',
'channel_data_id' => 2,
'value' => 'Some long text blah blah',
'field_id' => 2
)
)
Is there a better solution that iterating through the original array with a foreach loop?
Is there a better solution that iterating through the original array with a foreach loop
You know the split-key so there's no real use for foreach:
$src = array(...); // your source array
$fields_array = $src['fields'];
unset($src['fields']);
If I understood your question correct.
<?php
$base = array(...); // your array
// array values
$baseArrays = array_filter($base, function($item){
return is_array($item);
});
// not array values
$not = array_diff($base, $baseArrays);
As an alternative solution, if the fields key is always the last element of the array, you can use array_pop.
$fields = array_pop($array);
And that's it. Demo.
Related
I'm wanting to group my data by a specific value (parent name) and then merge all the items that share the same parent name under a "items" array
However it's overwriting the items array, not adding to it, so for example "items" in the output should have multiple items not just one.
Any ideas?
$result = array();
foreach ($page->products_codes as $option) {
$result[$option->parent->name]["title"] = $option->parent->title;
$result[$option->parent->name]["items"] = $option->title;
}
Outputs as:
array (
'fixture' =>
array (
'title' => 'Fixture',
'items' => 'Pinhole90 Fixed with LED51',
),
'finish' =>
array (
'title' => 'Finish',
'items' => 'RAL',
),
'ip-rating' =>
array (
'title' => 'IP Rating',
'items' => 'IP54',
),
'emergency' =>
array (
'title' => 'Emergency',
'items' => 'Maintained 3hr Self Test',
),
'installation' =>
array (
'title' => 'Installation',
'items' => 'Plaster-kit for seamless flush appearance',
),
'led' =>
array (
'title' => 'LED',
'items' => 'LED50 ONE',
),
'cct' =>
array (
'title' => 'CCT',
'items' => '90 CRI 4000K',
),
'beam-angle' =>
array (
'title' => 'Beam Angle',
'items' => '38°',
),
'protocol' =>
array (
'title' => 'Protocol',
'items' => 'Bluetooth',
),
'louvre-lens' =>
array (
'title' => 'Louvre/Lens',
'items' => 'Heavy Spread Lens',
),
)
Any thoughts?
Based on the preferred data structure you specified:
$result = array();
foreach ($page->products_codes as $option) {
$result[$option->parent->name]["title"] = $option->parent->title;
$result[$option->parent->name]["items"][] = $option;
}
$result = array_values($result);
Here's a working example: https://3v4l.org/u9XBk
I like an array to follow a defined structure like this:
array (
'id' => '',
'name' => '',
'quantity' => '',
)
This is the structure I would like to follow in a multidimensional array list. Example:
array (
array (
'id' => 'GFKHF312',
'name' => 'Item 1',
'quantity' => 1
),
array (
'id' => 'YUKKU134',
'name' => 'item 2',
'quantity' => 5
),
array (
'id' => 'TRUT243',
'name' => 'item 3',
'quantity' => 10
)
)
So I would like, to:
In every other name keys passed, when trying to add a new row to the list , it should be removed or filtered.
Example:
# When passed this data
array (
'id' => 'GFKHF312',
'name' => 'Item',
'quantity' => 1,
'new_key' => 120,
'other_key' => 'fsdfs',
)
# It should filter to this data
array (
'id' => 'GFKHF312',
'name' => 'Item',
'quantity' => 1
)
Second, if it doesn't have all the keys ('id', 'name', 'quantity') defined in structure it should fail (return false or null).
Example:
# When passed this data
array (
'id' => 'GFKHF312',
'quantity' => 1,
)
# It should return this data
false
Is it possibly to use a php array function, like array_diff, for that or cycles is needed to accomplish this.
Thanks for the help!
I want to remove a child array from a multi-dimensional array in case a duplicate value found for a particular key. The answer(s) here didn't work at all. The answer here works, however, for large amount of arrays, that gets pretty slower. Looking for a cleaner and faster solution.
Example PHP Array
$args = array();
$args[] = array(
'section' => array(
'id' => 'section1',
'name' => 'Section 1',
),
'name' => 'Shortcode Name',
'action' => 'shortcodeaction',
'icon' => 'codeicon',
'image' => 'codeimage',
);
$args[] = array(
'section' => array(
'id' => 'section2',
'name' => 'Section 2',
),
'name' => 'Shortcode2 Name',
'action' => 'shortcodeaction2',
'icon' => 'codeicon2',
'image' => 'codeimage2',
);
$args[] = array(
'section' => array(
'id' => 'section3',
'name' => 'Section 3',
),
'name' => 'Shortcode3 Name',
'action' => 'shortcodeaction3',
'icon' => 'codeicon3',
'image' => 'codeimage3',
);
$args[] = array(
'section' => array(
'id' => 'section1',
'name' => 'Section 4',
),
'name' => 'Shortcode4 Name',
'action' => 'shortcodeaction4',
'icon' => 'codeicon4',
'image' => 'codeimage4',
);
$args[] = array(
'section' => array(
'id' => 'section5',
'name' => 'Section 5',
),
'name' => 'Shortcode5 Name',
'action' => 'shortcodeaction5',
'icon' => 'codeicon5',
'image' => 'codeimage5',
);
$sections = array();
foreach ( $args as $arg ) {
$sections[] = $arg['section'];
}
And, the print_r($sections) result.
Array
(
[0] => Array
(
[id] => section1
[name] => Section 1
)
[1] => Array
(
[id] => section2
[name] => Section 2
)
[2] => Array
(
[id] => section3
[name] => Section 3
)
[3] => Array
(
[id] => section1
[name] => Section 4
)
[4] => Array
(
[id] => section5
[name] => Section 5
)
)
Both Array[0] and Array[3] has the same value for the key id, therefor the entire Array[3] has to be removed in my case to avoid duplicates.
This is working for me though, but it gets really slow when there are 100s or more arrays.
$knownIds = array();
foreach( $sections AS $key=>$item ) {
if( array_key_exists($item['id'], $knownIds) === true ) {
unset( $sections[$key] );
} else {
$knownIds[$item['id']] = $key;
}
}
$sections = array_values($sections);
Tried several answers here in StackOverflow (including this), but none of them helped in my case.
Thanks
You can modify the whole using array_column and array_filter -
//get all the sections value
$section = array_column($args, 'section');
//store ids in temp array
$idArray = array_unique(array_column($section, 'id'));
//filter the array having unique id
$uniqueSections = array_filter($section, function ($key, $value) use ($idArray) {
return in_array($value, array_keys($idArray));
}, ARRAY_FILTER_USE_BOTH);
var_dump($uniqueSections);
For PHP <5.5
$section = array_map(function($args) {
return $args['section'];
}, $args);
$idArray = array_unique(array_map(function($section){return $section['id'];}, $section));
I'm having a bit of trouble accessing data within an array that looks like the following:
array (
0 => array ( 'value' => '46', 'label' => 'Brand A', ),
1 => array ( 'value' => '45', 'label' => 'Brand B', ),
2 => array ( 'value' => '570', 'label' => 'Brand C', ),
);
Essentially I want to be able to return the contents of the label when given the value (e.g. 45 returns Brand B), but am not sure how to do this within these levels.
Do I need to break this array down into smaller chunks through a loop of some sort to access this data?
Thanks
When creating the array you need to use the value as the key:
array(
'46' => 'Brand A',
'45' => 'Brand B',
);
OR
$arrayVar['46'] = 'Brand A';
etc.
If you aren't the one creating the array, then you can foreach loop through it and rework it into a different structure.
<?php
$arr = array (
0 => array ( 'value' => '46', 'label' => 'Brand A', ),
1 => array ( 'value' => '45', 'label' => 'Brand B', ),
2 => array ( 'value' => '570', 'label' => 'Brand C', ),
);
$val = 45; // search for 45
foreach($arr as $vals){
if($vals['value'] == $val){
echo "value=".$vals['value'];
echo "<br>";
echo "label=".$vals['label'];
}
}
?>
Try this
<?php
$arr = array (
0 => array ( 'value' => '46', 'label' => 'Brand A', ),
1 => array ( 'value' => '45', 'label' => 'Brand B', ),
2 => array ( 'value' => '570', 'label' => 'Brand C', ),
);
foreach($arr as $ele){
echo "value=".$ele['value']." and label=".$ele['label'];
}
?>
I have an array:
$initialarray = array(
0 = array(
'unit' => 1,
'class' => 1,
'value' => 'string1'
),
1 = array(
'unit' => 1,
'class' => 2,
'value' => 'string2'
),
2 = array(
'unit' => 1,
'class' => 2,
'value' => 'string3'
),
3 = array(
'unit' => 2,
'class' => 1,
'value' => 'string4'
)
4 = array(
'unit' => 2,
'class' => 2,
'value' => 'string5'
)
);
What would be the best way to structure it (to group the resulting sub-arrays) depending first on the 'unit' field's values, and then depending on the 'class' field's values, like so:
$resultarray = array(
// array of all the sub-arrays of 'unit' = 1
$unit[1] = array(
// array of all the sub-arrays of 'unit' = 1 and 'class' = 1
$class[1] = array(
0 = array(
'unit' => 1,
'class' => 1,
'value' => 'string1'
)
)
// array of all the sub-arrays of 'unit' = 1 and 'class' = 2
$class[2] = array(
0 = array(
'unit' => 1,
'class' => 2,
'value' => 'string2'
),
1 = array(
'unit' => 1,
'class' => 2,
'value' => 'string3'
)
)
)
// array of all the sub-arrays of 'unit' = 2
$unit[2] = array(
// array of all the sub-arrays of 'unit' = 2 and 'class' = 1
$class[1] = array(
0 = array(
'unit' => 2,
'class' => 1,
'value' => 'string4'
)
)
// array of all the sub-arrays of 'unit' = 2 and 'class' = 2
$class[2] = array(
0 = array(
'unit' => 2,
'class' => 2,
'value' => 'string5'
)
)
)
)
I have asked a similar question here and got a working answer for only one iteration, i.e. for only structuring the array by one of the fields. But I could not make the same solution work for multiple iterations, i.e. for more than one field.
Also, is there a solution to structure a multidimensional array depending on more than two fields?
I think it's not a way of asking the question. It is very simple , you can do this by playing with arrays,keys and etc.... So first you should try hard for the problem. After If you have any problem in the middle of your tries then you can ask that here. I have solved your problem here is the complete code , but next time please do some work and then only post the problem. Never ask for the code.
foreach ($initialarray as $key1=>$val1)
{
foreach ($val1 as $key2=>$val2)
{
if($key2=='unit')
{
$num=$val2;
if($val2!=$num)
$testarr['unit'.$val2]=array();
}
if($key2=='class')
{
$testarr['unit'.$num]['class'.$val2][]=$val1;
}
}
}
print_r($testarr);
I must offer a better way for you and future researchers...
You only need one loop, and you merely need to nominate the result array's key values before using [] to "push" new data into the deepest subarray.
*there is absolutely no need for any condition statements or a second loop.
Code: (Demo)
$initialarray = [
['unit' => 1, 'class' => 1, 'value' => 'string1'],
['unit' => 1, 'class' => 2, 'value' => 'string2'],
['unit' => 1, 'class' => 2, 'value' => 'string3'],
['unit' => 2, 'class' => 1, 'value' => 'string4'],
['unit' => 2, 'class' => 2, 'value' => 'string5']
];
foreach ($initialarray as $row) {
$result[$row['unit']][$row['class']][] = $row;
}
var_export($result);
Output:
array (
1 =>
array (
1 =>
array (
0 =>
array (
'unit' => 1,
'class' => 1,
'value' => 'string1',
),
),
2 =>
array (
0 =>
array (
'unit' => 1,
'class' => 2,
'value' => 'string2',
),
1 =>
array (
'unit' => 1,
'class' => 2,
'value' => 'string3',
),
),
),
2 =>
array (
1 =>
array (
0 =>
array (
'unit' => 2,
'class' => 1,
'value' => 'string4',
),
),
2 =>
array (
0 =>
array (
'unit' => 2,
'class' => 2,
'value' => 'string5',
),
),
),
)
If I may express myself in the following manner: I only see the front-end of your problem and know nothing about its back-end, e.g. "Where does the data come from?", "How is it collected and stored", etc. so my answer might not be a real help but still I'll give my "tuppence".
If you can store all that data in a relational database (in form of table(s)) it would be much more easier and faster(!) to select the needed data from the database instead of rearranging arrays, which will take some more time in comparison.
Just as an example you might then select (and store it into an array) all items which have unit = '1' and / or all items which have class = '2'. That would make life much more easier IMHO, than having all the data in a multidimensional array and then try to sort it / rearrange it. Especially if you do that based on more than one property.