PHP How to push array into array[key]? - php

This is the code I have:
$orders = Array();
foreach ($unassigned as $uorder) {
$array = Array(
"ordid" => $uorder->idord,
"fecha" => $uorder->datorod,
"cliente" => $uorder->idcli
);
array_push($orders[$uorder->user_id], $array);
}
print_r($orders);
Which results:
Array (
[vendor1] =>
[vendor2] =>
)
I want to make some kind of sort
So I could use $orders[vendor1][0][ordid] to find the first order that the vendor made.

You have to assign $orders[$uorder->user_id] as an array first, otherwise it doesn't make sense to push an item onto it. Additionally, you can use the shorthand append notation:
if(!isset($orders[$uorder->user_id]))
$orders[$uorder->user_id] = array();
$orders[$uorder->user_id][] = $array;

In your foreach loop check if $orders[$uorder->user_id] is an array, if not create one.
foreach($unassigned as $uorder):
if(! is_array($orders[$uorder->user_id]))
$orders[$uorder->user_id] = array();
array_push($orders[$uorder->user_id],Array("ordid" => $uorder->idord, "fecha" => $uorder->datorod, "cliente" => $uorder->idcli));
endforeach;

Related

create nested array from string with delimiter

I has a string like as brachA-branchB-branchC. I am trying to make it as nested array as follows
[
'name'=>'brachA',
'sub'=> [
'name'=>'brachB',
'sub'=>[
'name'=>'brachC'
]
]
]
I tried as follows (https://3v4l.org/A781D)
<?php
$nested_array = array();
$temp = &$nested_array;
$item = 'brachA-branchB-branchC';
foreach (explode('-', $item) as $key => $value) {
$temp = &$temp[$value];
}
print_r($nested_array);
Output I am getting as follows
Array
(
[brachA] => Array
(
[branchB] => Array
(
[branchC] =>
)
)
)
Any idea, how to achieve this ?
It can probably be done using a foreach loop over the reversed array returned by explode() but it is much easier to use a recursive function.
function makeArray(array $pieces)
{
$first = array_shift($pieces);
$array = array('name' => $first);
if (count($pieces)) {
$array['sub'] = makeArray($pieces);
}
return $array;
}
$item = 'brachA-branchB-branchC';
print_r(makeArray(explode('-', $item)));
The makeArray() function receives an array with the string pieces. It puts the first item under the 'name' key of a new array and invokes itself with the rest of the array to generate the array to put under the 'sub' key. It doesn't put anything for the 'sub' key if there is no rest (on the last call, $pieces is array('brachC').

How to select and print only the value of a nested array?

I'm trying to create an array only from the basename of the url's of $member1 and $member2 and so on to $member(n).
the base array i'm using looks like this for a reason, since I'm using it for another foreach loop.
So the scheme looks like this:
$member1 = 'http://www.bla-bla.com/aFolder/anotherFolder';
$member2 = 'http://www.yada-yada.com/yetAnotherFolder/innerFolder';
$member3 = 'http://www.boo-boo.com/abcs/folder';
//this is the main array
$teams = array(
array("url" => $member1, "selector" => "a"),
array("url" => $member2, "selector" => "input"),
array("url" => $member3, "selector" => "h1"),...,...);
I would like to build a foreach that would create at the end an array with the values with basename($member(n)).
I would like my result to look like this:
Array
(
[0] => anotherFolder
[1] => innerFolder
[2] => folder
)
Thus far I've tried different ways to extract that specific value with no avail, I couldn't find a way on how to extract that specific value.
I'll appreciate the help.
$basenames = [];
foreach ($teams as $team) {
$basenames[] = basename($team['url']);
}
function getBaseName($array){
$return=array();
foreach($array as $arr)
{
$exp=explode("/",$arr['url']);
$return[]=array_pop($exp);
}
return $return;
}
$basenames[]=getBaseName($teams);
If I understood you right, try this:
$resArray = array();
foreach($teams as $team){
$resArray[] = basename($team['url']);
}
The solution using array_map and basename functions:
...
$result = array_map(function($v){ return basename($v['url']); }, $teams);
$array = array();
foreach($teams as $team){
$array[] = basename($team["url"]);
}
print_r($array);
will print
Array
(
[0] => anotherFolder
[1] => innerFolder
[2] => folder
)

PHP Remove Multidimensional Array Value

I have array multidimensional code like this:
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
unset($array[$eaten]);
and what i need is to delete 'grape' from the array because 'grape' already eaten. how to fix my code to unset the 'grape'?
and my question number two, if it can be unset, is there a way to unset multi value like
unset($array,['grape','orange']);
thanks for help..
You can remove eaten element by following way. Use array_search() you can find key at the position of your eaten element.
Here below code shows that in any multidimensional array you can call given function.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$eaten = 'grape';
$array = removeElement($array, $eaten);
function removeElement($data_arr, $eaten)
{
foreach($data_arr as $k => $single)
{
if (count($single) != count($single, COUNT_RECURSIVE))
{
$data_arr[$k] = removeElement($single, $eaten);
}
else
{
if(($key = array_search($eaten, $single)) !== false)
{
unset($data_arr[$k][$key]);
}
}
}
return $data_arr;
}
P.S. Please note that you can unset() multiple elements in single call. But the way you are using unset is wrong.
Instead of using unset() i suggest you to create a new Array after removal of required value benefit is that, your original array will remain same, you can use it further:
Example:
// your array
$yourArr = array(
'fruits'=>array('apple','orange','grape', 'pineaple'),
'vegetables'=>array('tomato', 'potato')
);
// remove array that you need
$removeArr = array('grape','tomato');
$newArr = array();
foreach ($yourArr as $key => $value) {
foreach ($value as $finalVal) {
if(!in_array($finalVal, $removeArr)){ // check if available in removal array
$newArr[$key][] = $finalVal;
}
}
}
echo "<pre>";
print_r($newArr);
Result:
Array
(
[fruits] => Array
(
[0] => apple
[1] => orange
[2] => pineaple
)
[vegetables] => Array
(
[0] => potato
)
)
Explanation:
Using this array array('grape','tomato'); which will remove the value that you define in this array.
This is how I would do it.
$array = [
'fruits' => ['apple','orange','grape', 'pineaple'],
'vegetables' => ['tomato', 'potato']
];
$unset_item = 'grape';
$array = array_map(function($items) use ($unset_item) {
$found = array_search($unset_item, $items);
if($found){
unset($items[$found]);
}
return $items;
}, $array);

Removing all array items except one array item

I have two array structures. I want to delete all array items in both array except one item in both array. I have written my codes below. How can I do that?
$array_one = array(
'image-one' => 'image-one.jpg',
'image-two' => 'image-two.jpg',
'image-three' => 'image-three.jpg',
'image-four' => 'image-four.jpg',
'image-five' => 'image-five.jpg',
'image-six' => 'image-six.jpg',
'image-seven' => 'image-seven.jpg',
);
$array_two = array(
'image-one' => 'image-one.jpg',
'image-two' => 'image-two.jpg',
'image-three' => 'image-three.jpg',
'image-four' => 'image-four.jpg',
);
I want to delete image-one.jpg,image-two.jpg,image-three.jpg in both arrays except image-four.jpg,image-five.jpg,image-six.jpg,image-seven.jpg.
Using unset:
unset($array['image-one']);
unset($array['image-two']);
unset($array['image-three']);
You can also create loop.
$todelete = array('image-one', 'image-two', 'image-three');
foreach($todelete as $del){
unset($array[$del]);
}
If you want to delete by value:
$todelete = array('image-one.jpg', 'image-two.jpg', 'image-three.jpg');
foreach($todelete as $del){
if(($key = array_search($del, $array)) !== false) {
unset($array[$key]);
}
}
You can use unset() :
unset($array_one['image-one']);
unset($array_one['image-two']);
unset($array_one['image-three']);

How to randomly loop through first layer of nested associative array in PHP?

I have a nested assocative array which might look something like this:
$myarray = array(
['tiger'] => array(
['people'], ['apes'], ['birds']
),
['eagle'] => array(
['rodents'] => array(['mice'], ['squirrel'])
),
['shark'] => ['seals']
);
How can I loop through the first layer (tiger, eagle, shark) in a random order and ensure that I cover them all in my loop? I was looking at the PHP function shuffle();, but I think that function messes up the whole array by shuffling all layers.
You can randomly sort an array like this, it will keep the keys and the values
<?php
$myarray = array(
'tiger' => array(
'people', 'apes', 'birds'
),
'eagle' => array(
'rodents' => array('mice', 'squirrel')
),
'shark' => 'seals'
);
$shuffleKeys = array_keys($myarray);
shuffle($shuffleKeys);
$newArray = array();
foreach($shuffleKeys as $key) {
$newArray[$key] = $myarray[$key];
}
print_r($newArray);
You can get the keys using array_keys(). Then you can shuffle the resulting key array using shuffle() and iterate through it.
Example:
$keys = array_keys($myarray);
shuffle($keys);
foreach ($keys as $key) {
var_dump($myarray[$key]);
}
According to my test, shuffle only randomizes 1 layer. try it yourself:
<?php
$test = array(
array(1,2,3,4,5),
array('a','b','c','d','e'),
array('one','two','three','four','five')
);
shuffle($test);
var_dump($test);
?>

Categories