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'];
}
?>
Related
This question already has answers here:
PHP getting sum of values group by key in array [duplicate]
(2 answers)
grouping of array in PHP [duplicate]
(2 answers)
How to sum array value of duplicate data
(5 answers)
Closed 1 year ago.
can someone explain me how to multiply the value from this code? i tried but still cant solve this
arrayK(
0 => array(
'name'=> AA,
'value' => 2.00,
),
1 => array(
'name' => AA,
'value' => 1.82,
),
2 => array(
'name' => BB,
'value' => 2.20,
),
3 => array(
'name' => AA,
'value' => 4.20,
),
4 => array(
'name' => BB,
'value' => 4.20,
),
);
the answer should back to array with value already multiply where it has same name
newArray(
0 => array(
'name'=> AA,
'value' => ...,
),
1 => array(
'name' => BB,
'value' => ....,
),
);
To multiply duplicate value and get new array:
$array=array(
0 => array(
'name'=> AA,
'value' => 2.00,
),
1 => array(
'name' => AA,
'value' => 1.82,
),
2 => array(
'name' => BB,
'value' => 2.20,
),
3 => array(
'name' => AA,
'value' => 4.20,
),
4 => array(
'name' => BB,
'value' => 4.20,
),
);
$result = array();
foreach ($array as $val) {
if (!isset($result[$val['name']]))
$result[$val['name']] = $val;
else
$result[$val['name']]['value'] *= $val['value'];
}
$result = array_values($result); // reindex array
echo "<pre>";
print_r($result);
You can try following solution.
$arrayK = array(
0 => array(
'name'=> "AA",
'value' => 2.00,
),
1 => array(
'name' => "AA",
'value' => 1.82,
),
2 => array(
'name' => "BB",
'value' => 2.20,
),
3 => array(
'name' => "AA",
'value' => 4.20,
),
4 => array(
'name' => "BB",
'value' => 4.20,
),
);
$temp = array_values((array_unique(array_column($arrayK, 'name'))));
$arrayY = [];
for( $i = 0; $i < count($temp); $i++ ) {
foreach( $arrayK as $key => $val ) {
if( $val['name'] == $temp[$i] ) {
$arrayY[$i] = [
'name' => $val['name'],
'value' => isset($arrayY[$i]['value']) ? $val['value'] * $arrayY[$i]['value'] : $val['value']
];
}
}
}
print_r($arrayY);
Out put
Array
(
[0] => Array
(
[name] => AA
[value] => 15.288
)
[1] => Array
(
[name] => BB
[value] => 9.24
)
)
You can play with the code Here
I have two array..
Array 1
$arr1 = array(
'task' => 'delete'
)
Array 2
$arr2 = array(
array(
'id' => '1',
'type' => 'post',
),
array(
'id' => '2',
'type' => 'category',
),
array(
'id' => '1',
'type' => 'tag',
),
);
How I insert Array 1 to all Array 2 collection, so the results is.
$arr2 = array(
array(
'id' => '1',
'task' => 'delete',
'type' => 'post',
),
array(
'id' => '2',
'task' => 'delete',
'type' => 'category',
),
array(
'id' => '1',
'task' => 'delete',
'type' => 'tag',
),
);
I can be easily to get the results by using looping, but I want to achieve it not using looping.
Any suggestion ?
Thank you :)
In order to push arraay1 in array2 all indexes, you can use the array_walk with a combination of array merge, you can see below code for instance
<?php
$array1 = array(
'task' => 'delete',
'before' =>'test'
);
$array2=array(
array(
'id' => '1',
'type' => 'post',
),
array(
'id' => '2',
'type' => 'category',
),
array(
'id' => '1',
'type' => 'tag',
),
);
array_walk($array2, function(&$newarray) use ($array1) {
$newarray = array_merge($newarray, $array1);
});
print_r($array2);
?>
array_walk -Apply a user supplied function to every member of an array while array_merge, Merge two arrays into one array
Result
Array (
[0] => Array ( [id] => 1 [type] => post [task] => delete [before] => test )
[1] => Array ( [id] => 2 [type] => category [task] => delete [before] => test )
[2] => Array ( [id] => 1 [type] => tag [task] => delete [before] => test ) )
Git Hub
https://github.com/fahadpatel/insert-array-into-array-without-loop
DEMO
You can use array_walk to skip writing the loop.
$arr1 = array(
'task' => 'delete'
);
$arr2 = array(
array(
'id' => '1',
'type' => 'post',
),
array(
'id' => '2',
'type' => 'category',
),
array(
'id' => '1',
'type' => 'tag',
),
);
array_walk($arr2, function(&$item) use ($arr1) {
$item = array_merge($item, $arr1);
});
You can see the documentation for array_walk here.
You may use array_map. It's looping behind the scenes, though (no real way around it), but at least you don't have to do it yourself:
$arr3 = array_map(static function ($entry) use ($arr1) {
return $entry + $arr1;
}, $arr2);
PHP 7.4 version:
$arr3 = array_map(static fn($entry) => $entry + $arr1, $arr2);
Demo: https://3v4l.org/2u2SR
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.
Consider this nested array:
$link = array(
'Level 1' => array(
'Monthly' => array(
'note' => 'Note 1 1',
'link' => '1.1.com',
),
'6 Month' => array(
'note' => 'Note 1 6',
'link' => '1.6.com',
),
),
'Level 2' => array(
'Monthly' => array(
'note' => 'Note 2.1',
'link' => '2.1.com',
),
'6 Month' => array(
'note' => 'Note 2.6',
'link' => '2.6.com',
),
),
How would I gracefully use a foreach to achieve the following:
if $var = 'Level 1' output
Monthly
6 Month
I'm suspecting I might need to do a loop inside a loop? I can iterate through the array, but am having trouble figuring out how to call the name of the sub-array...
<?php
$key = 'Level 1';
$link = array(
'Level 1' => array(
'Monthly' => array(
'note' => 'Note 1 1',
'link' => '1.1.com',
),
'6 Month' => array(
'note' => 'Note 1 6',
'link' => '1.6.com',
),
),
'Level 2' => array(
'Monthly' => array(
'note' => 'Note 2.1',
'link' => '2.1.com',
),
'6 Month' => array(
'note' => 'Note 2.6',
'link' => '2.6.com',
),
),
);
if(isset($link[$key])) {
foreach($link[$key] as $array) {
print_r($array);
}
}
?>
RETURNS
Array
(
[note] => Note 1 1
[link] => 1.1.com
)
Array
(
[note] => Note 1 6
[link] => 1.6.com
)
I check to see if it is set first and then run a foreach on the set key to print out what you need.
EDIT:
if(isset($link[$key])) {
foreach($link[$key] as $key => $array) {
print $key;
print_r($array);
}
}
Which returns
Monthly
Array
(
[note] => Note 1 1
[link] => 1.1.com
)
6 Month
Array
(
[note] => Note 1 6
[link] => 1.6.com
)
I think using nested loop in this case is graceful.
Just use two foreach.
that's how it'd look like if you're trying to define the arrays within the main array
foreach ($link as $sub_array) {
//do something
foreach ($sub_array as $sub_of_sub) {
// do something and so on
}
}
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.