Group data by first element of 2 dimensional array - PHP [duplicate] - php

This question already has answers here:
Prevent array overwriting and instead create new array index
(2 answers)
Closed 2 years ago.
I have this code.
$shirts = [
['xl','silk','blue'],
['xl', 'cotton', 'red'],
['L', 'silk', 'green'],
['L', 'silk', 'black']
];
I want to group size . For example, I want output like this
$shirtbysize = [
'xl' =>
[
['silk','blue'],
['cotton','red']
],
'L' =>
[
['silk','green'],
['silk','black']
],
];
I searched everywhere but I didn't get answer. Can anyone tell me how to do this?

Use array_shift to pick the first element and remove it from array.
array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be affected.
Use array_shift to pick the first element and set it as index.
Now first element is already removed from first step, set the remaining array as data to above index.
$shirtbysize = [];
foreach($shirts as $shirt){
$shirtbysize[array_shift($shirt)][] = $shirt;
}

Related

PHP search an array value inside an array in one line [duplicate]

This question already has an answer here:
Get key from first array on Search Array in Array PHP
(1 answer)
Closed 3 months ago.
I'm using PHP 7.4. I have this array :
$sections = [
'sectionOne' => [
'foo',
'bar',
'hello',
],
'sectionTwo' => [
'yo',
'heya',
],
];
I'd like to build a function to return the section of the received array value
public function getSectionByValue($value) {
return ...
}
If the value is bar then I'll get sectionOne. If the value is yo then I'll get sectionTwo etc...
How can I do to search an array value inside an array ? It is possible to do this in one line ?
You can do something like this inside getSectionByValue function if you really want an one liner.
return key(array_filter($sections, fn($section) => in_array($value, $section)));
If the provided value exists in multiple sections, it will just return the first one.

How to apply a filter to update element in array of arrays?

I am trying to create a PHP application that lets me uploading data to a MongoDB collection. For that I have "installed" the PHP driver with no problems.
However, I cannot find anyway -neither in the PHP guide- how could I update an element in an array of arrays.
Collection structure
As you may see, _unidades is an array of arrays. Each of those arrays contains an ID, a string and another array. In my case, which will be chosen depends on previous param -it has to match with element 1 of one of them.
Once I have selected that structure, I want to insert a new array into its array of arrays (position 2).
Regarding code, I tried the following:
$bulk = new MongoDB\Driver\BulkWrite();
$bulk->update(
[
'_isbn' => (int) $_POST["isbn"],
'_topics' =>
[
'0' => (int) $_POST["topic"]
]
],
[
'$set' => [
'1' => array($_POST["sentence"], $_POST["question"])
]
]
);
$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 100);
$resultado = $manager->executeBulkWrite('libreee.faq', $bulk, $writeConcern);
However as you can see I am not capable to determine at least that it doesn't have to be an specific array (7th line).
Once said that I look forward to receiving your help.
Thanks a lot in advance.
Regards,
Ciconia.

Find key in multidimensional array and change the value [duplicate]

This question already has answers here:
Get key of multidimensional array?
(5 answers)
Using a string path to set nested array data [duplicate]
(8 answers)
Closed 5 years ago.
I'm writing a PHP script in which I got a multidimensional array without fixed depth. Eg:
$myArray = [
'item01' => [
'section01' => [
'part01'
]
],
'item02' => [
'section02' => [
'part02' => [
'something01'
]
]
],
'item03' => [
'section03'
]
]
I have a string that contains the path to the value that should be changed. Eg:
$myPath = 'item02/section02/part02'
And I have the new value:
$myValue = 'somethingElse'
What I'm trying to do, is go through array $myArray following the path set in $myPath to change the value to $myValue.
The expected output, with the examples above, would be this:
$myArray = [
'item01' => [
'section01' => [
'part01'
]
],
'item02' => [
'section02' => [
'part02' => [
'somethingElse'
]
]
],
'item03' => [
'section03'
]
]
I've tried several ways, but keep getting stumped on this. In the end, it always reaches a point where the solution is, at its core, the same. Rubber duckying didn't help either. Other programmers I know, haven't been able to find a solution either.
I'm hoping someone here can at least provide some fresh ways to look into this.
PS: Everything above is in pseudo-code, as this problem doesn't seem to be language-specific.
try the following:
$myPath = 'item02/section02/part02';
$path = explode('/', $myPath);
$arr = &$myArray;
foreach($path as $key)
{
$arr = &$arr[$key];
}
$arr = "somethingElse";
var_dump($myArray);
First turn the $myPath string into an array of keys using explode.
This uses a simple loop foreach loop to loop over the array using keys, and then by passing the values by reference it replaces the deepest value. Demo Here

how to use array_push() [duplicate]

This question already has answers here:
Add values to an associative array in PHP
(2 answers)
Closed 7 years ago.
I want to push new data in array which each value of them.
$array = array("menu1" => "101", "menu2" => "201");
array_push($array, "menu3" => "301");
But I got an error syntax.
And if I use like this :
$array = array("menu1" => "101", "menu2" => "201");
array_push($array, "menu3", "301");
result is : Array ( [menu1]=>101 [menu2]=>201 [0]=>menu3 [1]=>301 )
My hope the result is : Array ( [menu1]=>101 [menu2]=>201 [menu3]=>301 )
I want push new [menu3]=>'301' but I dont know how. Please help me, the answer will be appreciate
You can use
$array["menu3"] = "301"
as for array_push
array_push() treats array as a stack, and pushes the passed variables onto the end of array
so for associative arrays is a no match
another suitable function for what you want but it requires an array argument is array_merge
$result = array_merge(array("one" => "1"), array("two" => "2"));

How to get key value of array? [duplicate]

This question already has answers here:
Getting the key of the only element in a PHP array
(6 answers)
Closed 8 years ago.
How do I get the value of a key of any array item? Like how a foreach loop turns it into $k => $v...except I only want to do that once, so no need for a loop. Do I really need to make a new array that it flips to?
Take this for example.
1 => array(
'street' => 'Street Address ',
'town' => 'Town/City '
),
2 => array(
'state' => 'State '
),
Those are arrays inside a bigger array. And now I tried to do this
array_flip($thatarrayupthere[2]['state'])
What I want to receive from that is "state" because that is the key name. But I'm getting errors.
I'm not exactly sure what you wan't, but if you just want to get the key of the second array in any given array this might help.
$key = key($array[2]);
In your example above you will get "state" in your $key variable.
$key = array_keys($array[2]);
print_r($key);
ref: http://php.net/manual/en/function.array-keys.php

Categories