PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label multidimensional-array. Show all posts
Showing posts with label multidimensional-array. Show all posts

Tuesday, September 20, 2022

[FIXED] How to print multiple Employee details with below requirement which collection type can be used in java?

 September 20, 2022     arrays, hashmap, java, multidimensional-array     No comments   

Issue

I want to store data as below format to any function of java collection and print the output:-

[
   { id->100, name->'praveen', mobile-9455104973 },
   { id->101, name->'Saurbh', mobile-7355078643 },
   { id->103, name->'Shivendr', mobile-123456789 } 
]

Output:

ID   Name       Mobile
100  Praveen    9455104973
101  Saurbh     735078643
102  Shivendra  123456789

Solution

I recommend that you create an employee class.

public class Employee {
private int id;
private String name;
private long phoneNumber;

/**
 * @param id
 * @param name
 * @param phoneNumber
 */
public Employee(int id, String name, long phoneNumber) {
    super();
    this.id = id;
    this.name = name;
    this.phoneNumber = phoneNumber;
}

@Override
public String toString() {
    return id + "\t" + name + "\t" + phoneNumber + "\n";
}
}

After that you create a list of employees and initialize it with the employees you are interested in and print it.

List<Employee> employees = new ArrayList<>();
    employees.add(new Employee(100, "praveen", 9455104973L));
    employees.add(new Employee(101, "Saurbh", 7355078643L));
    employees.add(new Employee(103, "Shivendr", 123456789L));
    
    System.out.println("ID\tName\tMobile");
    
    for (Employee e: employees)
        System.out.println(e.toString());

OUTPUT:

ID  Name    Mobile
100 praveen 9455104973

101 Saurbh  7355078643

103 Shivendr    123456789


Answered By - Fede Cana
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, August 17, 2022

[FIXED] How to convert a PHP multi-dimensional array into another array based on a value within the original array(s)?

 August 17, 2022     arrays, multidimensional-array, object, output, php     No comments   

Issue

I have spent a week on this, and I am trying to come up with a way to access the data in the multi-dimensional array and output it to another array, restructured differently, based on a value within the array. Rather than post rows and rows of broken code, I present my example simplified:

Here is the original array:

array(2) {
    [0] => array(2) {
        ["aaa"] => array(2) {
            ["a19a3234b881ce"] => array(2) {
                ["pid"] => int(29301)
                ["vid"] => int(29334)
                ["idx"] => int(88888)
            }
            ["a7aa94c38aa49caa"] => array(2) {
                ["pid"] => int(20568)
                ["vid"] => int(26547)
                ["idx"] => int(88888)
            }
        }
        ["bbb"] => array(2) {
            ["bsfn"] => string(4) "Apple"
            ["bsln"] => string(8) "AppleApple"
        }
    }
    [1] => array(2) {
        ["aaa"] => array(3) {
            ["abd296a10"] => array(2) {
                ["pid"] => int(56734)
                ["vid"] => int(98612)
                ["idx"] => int(99999)
            }
            ["a31e920fde8"] => array(2) {
                ["pid"] => int(09800)
                ["vid"] => int(34521)
                ["idx"] => int(99999)
            }
            ["a7aa94c38aa49caa"] => array(2) {
                ["pid"] => int(20568)
                ["vid"] => int(26547)
                ["idx"] => int(99999)
            }
        }
        ["bbb"] => array(2) {
            ["bsfn"] => string(4) "Ball"
            ["bsln"] => string(8) "BallBall"
        }
    }
}

Here is what I want to output:

array(2) {
    ["88888"] => array(3) {
        ["a19a3234b881ce"] => array(4) {
            ["pid"] => int(29301)
            ["vid"] => int(29334)
            ["idx"] => int(88888)
            ["arr"] => string(14) "a19a3234b881ce"
        }
        ["a7aa94c38aa49caa"] => array(4) {
            ["pid"] => int(20568)
            ["vid"] => int(26547)
            ["idx"] => int(88888)
            ["arr"] => string(16) "a7aa94c38aa49caa"
        }
        ["bbb"] => array(2) {
            ["bsfn"] => string(4) "Apple"
            ["bsln"] => string(8) "AppleApple"
        }
    }
    ["99999"] => array(4) {
        ["abd296a10"] => array(4) {
            ["pid"] => int(29301)
            ["vid"] => int(29334)
            ["idx"] => int(99999)
            ["arr"] => string(9) "abd296a10"
        }
        ["a31e920fde8"] => array(4) {
            ["pid"] => int(20568)
            ["vid"] => int(26547)
            ["idx"] => int(99999)
            ["arr"] => string(11) "a31e920fde8"
        }
        ["a7aa94c38aa49caa"] => array(4) {
            ["pid"] => int(20568)
            ["vid"] => int(26547)
            ["idx"] => int(99999)
            ["arr"] => string(16) "a7aa94c38aa49caa"
        }
        ["bbb"] => array(2) {
            ["bsfn"] => string(4) "Ball"
            ["bsln"] => string(8) "BallBall"
        }
    }
}

Solution

Try this example:

$result = [];
foreach($data as $item) {
    if (!empty($item['aaa']) && is_array($item['aaa'])) {
        $key = array_values($item['aaa'])[0]['idx'] ?? null;
        if ($key) {
            $result[$key] = array_merge($item['aaa'], ['bbb' => $item['bbb'] ?? []]);
        }
    }
}

// Test result:
print_r($result);


Answered By - id'7238
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, August 15, 2022

[FIXED] How does this nested loop output a list separated into 3 sections with 3 words in each section?

 August 15, 2022     c#, for-loop, multidimensional-array, nested-loops, output     No comments   

Issue

I'm very new to C#. I was curious on how this block of code printed out 3 separate lines with the 3 words in the arrays. Could someone explain how it works?

using System;

namespace MyFirstProgram
{
    class Program 
    {
        static void Main(string[] args)
        {

            String[,] parkingLot = {{ "Mustang", "F-150", "Explorer" }, { "Corvette", "Camaro", "Silverado" }, { "Corolla", "Camry", "Rav4" }};

            for(int i = 0; i < parkingLot.GetLength(0); i++)
            {
                for (int j = 0; j < parkingLot.GetLength(1); j++)
                {
                    Console.Write(parkingLot[i, j] + " ");
                }
                Console.WriteLine();
            }

            Console.ReadKey();
        }
    }
}```

Solution

The GetLength() method returns the size of the dimension passed in:

Gets a 32-bit integer that represents the number of elements in the specified dimension of the Array.

Notice the first call gets passed a zero:

parkingLot.GetLength(0)

This returns the number of ROWS in the 2D array.

The second call is passed a one:

parkingLot.GetLength(1)

Which tells you the number of COLUMNS in the 2D array.

Perhaps this example will illustrate the concept better:

String[,] parkingLot = {
  { "a", "b", "c" },
  { "1", "2", "3" },
  { "red", "green", "blue" },
  { "cat", "dog", "fish"},
  { "A1", "B2", "C3"}
};

for(int row = 0; row < parkingLot.GetLength(0); row++) // 5 rows
{
  for (int col = 0; col < parkingLot.GetLength(1); col++) // 3 columns
  {
    Console.Write(parkingLot[row, col] + " ");
  }
  Console.WriteLine();
}

Output:

a b c 
1 2 3 
red green blue 
cat dog fish 
A1 B2 C3 


Answered By - Idle_Mind
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, July 4, 2022

[FIXED] How can I recursively search for and replace values inside of an unknown-depth multidimensional PHP array?

 July 04, 2022     json, multidimensional-array, pass-by-reference, php, recursion     No comments   

Issue

I'm working with a JSON string. I'm converting it to an associative array to find specific values and change those values when a certain key is found (['content']). The depth of the array is always unknown and will always vary.

Here is the function I wrote. It takes an array as an argument and passes it by reference so that the variable itself is modified rather than a copy of it scoped locally to that function.

$json_array = json_decode($json_string, true);

function replace_data(&$json_array, $data='REPLACE TEST')
{
   foreach($json_array as $key => $value) {
       if ($key == 'content' && !is_array($value)) {
           $json_array[$key] = $data;

       } else {
           if (is_array($value)) {
               replace_data($value, $data);
           }
       }
   }

}


replace_data($json_array, "test test test");
var_dump($json_array);

What I'm expecting to happen is every time a key ['content'] is found at no matter what depth, it replaces with that value specified in the $data argument.

But, when I var_dump($json_array) Those values are unchanged.

What am I missing?


Solution

With array_walk_recursive:

function replace_data($json_array, $data = 'REPLACE TEST') {
    array_walk_recursive($json_array, function (&$value, $key) use ($data) {
        if (!is_array($value) && $key === 'content') {
            // $value passed by reference
            $value = $data;
        }
    });
    return $json_array;
}

And without references:

function replace_data($json_array, $data = 'REPLACE TEST') {
    foreach ($json_array as $key => $value) {
        if (is_array($value)) {
            $json_array[$key] = replace_data($value, $data);
        } elseif ($key === 'content') {
            $json_array[$key] = $data;
        }
    }
    return $json_array;
}


Answered By - Timurib
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, May 17, 2022

[FIXED] How to get an array with states as key and cities as value from the json array in PHP

 May 17, 2022     arrays, associative-array, multidimensional-array, php     No comments   

Issue

I have a json array which is somethig like this:

[
    {
        "CITY": "Horseheads",
        "STATE": "NY"
    },
    {
        "CITY": "Auburn",
        "STATE": "AL"
    },
    {
        "CITY": "Hurst",
        "STATE": "TX"
    },
    {
        "CITY": "Mesquite",
        "STATE": "TX"
    },
    {
        "CITY": "Arlington",
        "STATE": "TX"
    }
]

I want to create an array out of this which has states abbr as key and cities as values of that key. Example is below:

Array (
    [NY] => Array(
        Horseheads
    )
    [AL] => Array(
        Auburn
    )
    [TX] => Array(
        Hurst,
        Mesquite
        Arlington
    )
)

So far, what I've tried is, I've creted 2 separate arrays as cities and staes and combined them as shown below:

$cities = array_column($jsonArray, 'CITY');
$states = array_column($jsonArray, 'STATE');

$newArray = array_combine($states,$cities);

Which gives me results like this:

Array (
    [NY] => Horseheads
    [AL] => Auburn
    [TX] => Hurst
)

I am unable to get the result I want. Is it possible? Any help, hints or suggestions are appreciated.

Thanks


Solution

A simple loop will do that quite easily

$json_string = '[
    {"CITY": "Horseheads","STATE": "NY"},
    {"CITY": "Auburn","STATE": "AL"},
    {"CITY": "Hurst","STATE": "TX"},
    {"CITY": "Mesquite","STATE": "TX"},
    {"CITY": "Arlington","STATE": "TX"}
]';

// convert the JSON String into a PHP data type, 
// an array of objects in this case
$array = json_decode($json_string);

Initialise a new array to hold the result of your processing
$new = [];

// Loop over the array to get one object at a time
foreach ( $array as $obj){
    // add the bits of that object into you new array
    // making the State code the key will create an array of statecodes
    // using the [] in `$new[ $obj->STATE ][]` will add a new entry to the 
    // sub array under that state code when duplicate state codes are seen
    $new[ $obj->STATE ][] = $obj->CITY;
}

print_r($new);

RESULT

Array
(
    [NY] => Array
        (
            [0] => Horseheads
        )
    [AL] => Array
        (
            [0] => Auburn
        )
    [TX] => Array
        (
            [0] => Hurst
            [1] => Mesquite
            [2] => Arlington
        )
)


Answered By - RiggsFolly
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to loop a tree array with unknown depth and get array blocks?

 May 17, 2022     multidimensional-array, php, tree     No comments   

Issue

I found this solution to loop and print an unknown depth array:

    printAllValues($arr);

    function printAllValues($arr) {
        if(!is_array($arr)) {
            echo ($arr);
            return;
        }
        foreach($arr as $k => $v) {
            printAllValues($v);
        }
    }

But this solution prints each array value individually. I want to get (id, name, is_master) at once and save into db. Not each one individually. The array to loop looks like it:

Array
(
    [data] => Array
        (
            [0] => Array
                (
                    [id] => 0ea8a4ab99694ce7b74f08ed7fc4602e
                    [name] => xxxxxxx
                    [is_master] => 
                    [master_id] => ce93cab80820446290f7ea627578e6e9
                    [has_children] => 1
                    [nodes] => Array
                        (
                            [0] => Array
                                (
                                    [id] => 431169710c83410d841ab3cce079a0fd
                                    [name] => xxxxxxxxxxx
                                    [is_master] => 
                                    [master_id] => 0ea8a4ab99694ce7b74f08ed7fc4602e
                                    [has_children] => 
                                    [nodes] => 
                                )

                            [1] => Array
                                (
                                    [id] => 98e15adfd57c4285981781590e112d32
                                    [name] => xxxxxxxxx
                                    [is_master] => 
                                    [master_id] => 0ea8a4ab99694ce7b74f08ed7fc4602e
                                    [has_children] => 1
                                    [nodes] => Array
                                    ....

And I want to loop and save each block like this into db:

            [id] => 0ea8a4ab99694ce7b74f08ed7fc4602e
            [name] => xxxxxxx
            [is_master] => 
            [master_id] => 1234567

Solution

If you just want to process when encountering these values then you can do this:

function printAllValues($arr) {
    if (!is_array($arr)) {
        // don't process this
        return;
    }

    if (
        isset($arr["id"]) &&
        isset($arr["name"]) &&
        isset($arr["is_master"]) &&
        isset($arr["master_id"])
    ) {
        // all array keys exist
        // process data
    }

    foreach ($arr as $k => $v) {
        printAllValues($v);
    }
}

If you want to retrieve all the values, we can adjust that further and return a "simplified" array of these values

function getAllValues($arr, $values = []) {
    if (!is_array($arr)) {
        // no modifications, return original array
        return $values;
    }

    if (
        isset($arr["id"]) &&
        isset($arr["name"]) &&
        isset($arr["is_master"]) &&
        isset($arr["master_id"])
    ) {
        // all array keys exist
        // store data
        $values[] = [
            "id" => $arr["id"],
            "name" => $arr["name"],
            "is_master" => $arr["is_master"],
            "master_id" => $arr["master_id"],
        ];
    }

    foreach ($arr as $k => $v) {
        $values = getAllValues($v, $values);
    }

    return $values;
}

$simplified = getAllValues($arr);

echo json_encode($simplified);
/* Example Output
[
    {
        "id": "1",
        "name": "1",
        "is_master": "1",
        "master_id": "1"
    },
    {
        "id": "2",
        "name": "2",
        "is_master": "1",
        "master_id": "2"
    }
]
*/

NOTE: these are simple examples trying to match your code structure, there are many different ways to do this



Answered By - Rylee
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to sort an array of associative arrays by value of a given key in PHP?

 May 17, 2022     arrays, multidimensional-array, php, sorting     No comments   

Issue

Given this array:

$inventory = array(

   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),
   array("type"=>"pork", "price"=>5.43),

);

I would like to sort $inventory's elements by price to get:

$inventory = array(

   array("type"=>"pork", "price"=>5.43),
   array("type"=>"fruit", "price"=>3.50),
   array("type"=>"milk", "price"=>2.90),

);

How can I do this?


Solution

You are right, the function you're looking for is array_multisort().

Here's an example taken straight from the manual and adapted to your case:

$price = array();
foreach ($inventory as $key => $row)
{
    $price[$key] = $row['price'];
}
array_multisort($price, SORT_DESC, $inventory);

As of PHP 5.5.0 you can use array_column() instead of that foreach:

$price = array_column($inventory, 'price');

array_multisort($price, SORT_DESC, $inventory);


Answered By - Josh Davis
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, May 16, 2022

[FIXED] How to remove from a multidimensional array all duplicate elements including the original?

 May 16, 2022     arrays, multidimensional-array, php     No comments   

Issue

I am using php 7.1.

I have seen that to eliminate the duplicate elements it is enough with this

array_unique($array, SORT_REGULAR);

I've also seen this work

array_map("unserialize", array_unique(array_map("serialize", $array)));

But that only deletes the elements that are duplicated from the array, I want to delete those that are duplicated but I don't want it to leave me only 1 without a duplicate, I want it to also delete that original on which it has been based to verify that it is duplicated

How could I do it?

For example i have this

$array = array(
    [0] = array(
        [id] => 1,
        [number] => 12345,
        [date] => 2022-05-09
    )
    [1] = array(
        [id] => 2,
        [number] => 123456,
        [date] => 2022-05-09
    )
    [2] = array(
        [id] => 3,
        [number] => 123456,
        [date] => 2022-05-09
    )
    [3] = array(
        [id] => 3,
        [number] => 123456,
        [date] => 2022-05-09
    )
)

How can i let it become this:?

    $array = array(
        [0] = array(
            [id] => 1,
            [number] => 12345,
            [date] => 2022-05-09
        )
        [1] = array(
            [id] => 2,
            [number] => 123456,
            [date] => 2022-05-09
        )
)

Solution

This should be straightforward. Pluck all IDs using array_column and use array_count_values to get counts of occurrences of each ID. Then, use array_filter to filter only unique ones.

<?php

$unique_ids = array_count_values(array_column($array,'id'));
$res = array_filter($array, fn($v) => $unique_ids[$v['id']] === 1);
print_r($res);

Online Demo



Answered By - nice_dev
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, May 13, 2022

[FIXED] How to append a new element into 3D numpy array in a loop?

 May 13, 2022     append, insert, multidimensional-array, numpy, python     No comments   

Issue

I wanted to try to add a new element into the 3D numpy array in loop python but it didn't work with insert or append.

import numpy as np
a = np.array([[[24,24,3],[25,28,1],[13,34,1],[3,4,5]]])
a = np.insert(a,3,0,axis = 2)
print(a)
[[[24 24  3  0]
 [25 28  1  0]
 [13 34  1  0]
 [ 3  4  5  0]]]

I don't want to insert 0 to each array but with a for loop

for i in range(4):
 .......

The result should be like this:

[[[24 24  3  0]
 [25 28  1  1]
 [13 34  1  2]
 [ 3  4  5  3]]]

Solution

You can't do this piecemeal. Think rather terms of concatenating a wwhole column or plane at once. The array has to remain 'rectangular' - no raggedness.

In [276]: a = np.array([[[24,24,3],[25,28,1],[13,34,1],[3,4,5]]])
In [277]: a.shape
Out[277]: (1, 4, 3)
In [278]: x = np.arange(4).reshape(1,4,1)
In [279]: x
Out[279]: 
array([[[0],
        [1],
        [2],
        [3]]])
In [280]: arr1 =np.concatenate((a,x), axis=2)
In [281]: arr1.shape
Out[281]: (1, 4, 4)
In [282]: arr1
Out[282]: 
array([[[24, 24,  3,  0],
        [25, 28,  1,  1],
        [13, 34,  1,  2],
        [ 3,  4,  5,  3]]])

alternatively

In [290]: arr2=np.zeros((1,4,4),int)
In [291]: arr2[:,:,:3]=a
     ...: arr2
Out[291]: 
array([[[24, 24,  3,  0],
        [25, 28,  1,  0],
        [13, 34,  1,  0],
        [ 3,  4,  5,  0]]])
In [292]: for i in range(4):
     ...:     arr2[:,i,3]=i
     ...: 
In [293]: arr2
Out[293]: 
array([[[24, 24,  3,  0],
        [25, 28,  1,  1],
        [13, 34,  1,  2],
        [ 3,  4,  5,  3]]])


Answered By - hpaulj
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, May 10, 2022

[FIXED] Why is B = numpy.dot(A,x) so much slower looping through doing B[i,:,:] = numpy.dot(A[i,:,:],x) )?

 May 10, 2022     multidimensional-array, numpy, product, python     No comments   

Issue

I'm getting some efficiency test results that I can't explain.

I want to assemble a matrix B whose i-th entries B[i,:,:] = A[i,:,:].dot(x), where each A[i,:,:] is a 2D matrix, and so is x.

I can do this three ways, to test performance I make random (numpy.random.randn) matrices A = (10,1000,1000), x = (1000,1200). I get the following time results:

(1) single multidimensional dot product

B = A.dot(x)

total time: 102.361 s

(2) looping through i and performing 2D dot products

   # initialize B = np.zeros([dim1, dim2, dim3])
   for i in range(A.shape[0]):
       B[i,:,:] = A[i,:,:].dot(x)

total time: 0.826 s

(3) numpy.einsum

B3 = np.einsum("ijk, kl -> ijl", A, x)

total time: 8.289 s

So, option (2) is the fastest by far. But, considering just (1) and (2), I don't see the big difference between them. How can looping through and doing 2D dot products be ~ 124 times faster? They both use numpy.dot. Any insights?

I include the code used for the above results just below:

import numpy as np
import numpy.random as npr
import time

dim1, dim2, dim3 = 10, 1000, 1200
A = npr.randn(dim1, dim2, dim2)
x = npr.randn(dim2, dim3)

# consider three ways of assembling the same matrix B: B1, B2, B3

t = time.time()
B1 = np.dot(A,x)
td1 = time.time() - t
print "a single dot product of A [shape = (%d, %d, %d)] with x [shape = (%d, %d)] completes in %.3f s" \
  % (A.shape[0], A.shape[1], A.shape[2], x.shape[0], x.shape[1], td1)


B2 = np.zeros([A.shape[0], x.shape[0], x.shape[1]])
t = time.time()
for i in range(A.shape[0]):
    B2[i,:,:] = np.dot(A[i,:,:], x)
td2 = time.time() - t
print "taking %d dot products of 2D dot products A[i,:,:] [shape = (%d, %d)] with x [shape = (%d, %d)] completes in %.3f s" \
  % (A.shape[0], A.shape[1], A.shape[2], x.shape[0], x.shape[1], td2)

t = time.time()
B3 = np.einsum("ijk, kl -> ijl", A, x)
td3 = time.time() - t
print "using np.einsum, it completes in %.3f s" % td3

Solution

With smaller dims 10,100,200, I get a similar ranking

In [355]: %%timeit
   .....: B=np.zeros((N,M,L))
   .....: for i in range(N):
              B[i,:,:]=np.dot(A[i,:,:],x)
   .....: 
10 loops, best of 3: 22.5 ms per loop
In [356]: timeit np.dot(A,x)
10 loops, best of 3: 44.2 ms per loop
In [357]: timeit np.einsum('ijk,km->ijm',A,x)
10 loops, best of 3: 29 ms per loop

In [367]: timeit np.dot(A.reshape(-1,M),x).reshape(N,M,L)
10 loops, best of 3: 22.1 ms per loop

In [375]: timeit np.tensordot(A,x,(2,0))
10 loops, best of 3: 22.2 ms per loop

the itererative is faster, though not by as much as in your case.

This is probably true as long as that iterating dimension is small compared to the other ones. In that case the overhead of iteration (function calls etc) is small compared to the calculation time. And doing all the values at once uses more memory.

I tried a dot variation where I reshaped A into 2d, thinking that dot does that kind of reshaping internally. I'm surprised that it is actually fastest. tensordot is probably doing the same reshaping (that code if Python readable).


einsum sets up a 'sum of products' iteration involving 4 variables, the i,j,k,m - that is dim1*dim2*dim2*dim3 steps with the C level nditer. So the more indices you have the larger the iteration space.



Answered By - hpaulj
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, April 20, 2022

[FIXED] How to groupBy the collection of Laravel with the nested field of type array?

 April 20, 2022     collections, group-by, laravel, multidimensional-array     No comments   

Issue

I have this collection, and I want to change this data in order that the key will be the branches id and the value will be the items:

{
    "data": [
        {
            "id": 5020,
            "category_id": 577,
            "branches": [
             {
               "id": 7,
               "title": "water",
             },
             {
               "id": 6,
               "title": "vegetable",
             }, 
        },
        {
            "id": 5025,
            "category_id": 577,
            "branches": [
             {
               "id": 7,
               "title": "water",
             },
        }
     ]
}

I want to group by this data by branches -> id , something like this:

{
    "data": [
        "7" : [
               {
                 "id": 5020,
                 "category_id": 577,
                 "branches": [
                    {
                       "id": 7,
                       "title": "water",
                    },
                    {
                       "id": 6,
                       "title": "vegetable",
                    }, 
               },
              {
                "id": 5025,
                "category_id": 577,
                "branches": [
                  {
                    "id": 7,
                    "title": "water",
                  },
                ] 
             }
           ],
        "6" : [
               {
                 "id": 5020,
                 "category_id": 577,
                 "branches": [
                    {
                       "id": 7,
                       "title": "water",
                    },
                    {
                       "id": 6,
                       "title": "vegetable",
                    }, 
               },

           ],
}

How can I use the group By method of collection in Laravel? I want to have data like this and my data is the type of collection


Solution

You can use a callback in groupBy method to provide custom logic.

Example:

collect($data)->groupBy(fn($item, $key) => $item['branches'][0]['id']);

But in this example I want to suggest you to use loop:

$myGroups = [];
foreach($data as $item) {
  foreach($item['branches'] as $branch) {
    $myGroups[$branch['id']][] = $item;
  }
}


Answered By - Harven
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, March 19, 2022

[FIXED] Multi dimensional array in YII2

 March 19, 2022     api, multidimensional-array, yii     No comments   

Issue

I have been trying to create a folder concept in my application.
I tried to return the o/p in json format for APi. I am trying to list the folder,sub folder and the files in sub folder,but when I tried to nested array like this

{
  "success_msg": 1,
  "message": "success",
  "details": [
    {
      "foldername": "Test_folder_1",
      "subfolder": [
        {
          "sub_folder_name": "Test_sub_folder_1",

      "subfile": [
        {
          "filename": "test_1.pdf"
        },
        {
          "filename": "test_2.pdf"
        }
      ]
        },
        {
          "sub_folder_name": "test_folder",
 "subfile": [
        {
          "filename": "test_3.jpg"
        }
      ]
        }
      ]
    }
  ]
}

I am getting wrong o/p.Let me share with you that

{
  "success_msg": 1,
  "message": "success",
  "details": [
    {
      "foldername": "Test_folder_1",
      "subfolder": [
        {
          "sub_folder_name": "Test_sub_folder_1"
        },
        {
          "sub_folder_name": "test_folder"
        }
      ],
      "subfile": [
        {
          "filename": "test_1.pdf"
        },
        {
          "filename": "test_2.pdf"
        },
        {
          "filename": "test_3.jpg"
        }
      ]
    },
    {
      "foldername": "sample_folder",
      "subfolder": [],
      "subfile": []
    }
  ]
}  

And this is my action

public function actionFiles() {
    ob_start();
    $raw = file_get_contents("php://input");
    $obj = json_decode($raw);
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    if ($obj!=null){  
        $user_id            = $obj->cur_user_id;
        $user_model         = User::find()->where(['id'=>$user_id])->one();
        $developer_id       = $user_model->createdby;
        $folder_model       = Folder::find()->where(['developerid'=>$developer_id,'foldertype'=>'parent'])->all();
        $count_folder       = count($folder_model);
        if($count_folder > '0'){
            $response = ['success_msg' => 1, 'message' => 'success', 'details' => []];
            foreach($folder_model as $folder) {
                $folder_id                          = $folder['id'];
                $userdet['foldername']              = $folder['foldername'];
                $sub = [];
                $sub_files = [];
            $subfolder_model = Folder::find()->where(['folderid'=>$folder_id])->all();
            foreach ($subfolder_model as $subfolder) {
                $sub_folder_id              = $subfolder['id'];
                $sub_name['sub_folder_name'] = $subfolder['foldername'];
            $sub_file = Files::find()->where(['folderid'=>$folder_id,'subfolderid'=>$sub_folder_id])->all();
            foreach ($sub_file as $file) {
                $filename['filename'] = $file['filename'];
                array_push($sub_files, $filename);
            }
                array_push($sub, $sub_name);                
                // echo '<pre>';print_r($userdet);
            }

                $userdet['subfolder'] = $sub;               
                $userdet['subfile'] = $sub_files;
                array_push($response['details'], $userdet);

            }
            echo json_encode($response);
        }else {
                // failed to insert row  
            $response["success_msg"] = 2;
            $response["message"] = "No News found";
            echo json_encode($response);
        }

    } else {
        $response["success_msg"] = 3;
        $response["message"] = "Data missing";
        echo json_encode($response);
    }
}  

Can anyone tell me how can I insert sub file array in sub folder array...
thanks in advance..


Solution

I updated the code with some changes in position of the arrays.

if ($count_folder > '0') {
                $response = ['success_msg' => 1, 'message' => 'success', 'details' => []];
                foreach ($folder_model as $folder) {
                    $folder_id              = $folder['id'];
                    $userdet['foldername']  = $folder['foldername'];
                    $sub                    = [];
                    $subfolder_model        = Folder::find()->where(['folderid' => $folder_id])->all();
                    foreach ($subfolder_model as $subfolder) {
                    $sub_files              = [];
                        $sub_folder_id                  = $subfolder['id'];
                        $sub_name['sub_folder_name']    = $subfolder['foldername'];
                        $sub_file = Files::find()->where(['folderid' => $folder_id, 'subfolderid' => $sub_folder_id])->all();
                            echo '<pre>';print_r($sub_file);

                        foreach ($sub_file as $file) {
                            $filename['filename']       = Yii::$app->urlManager->createAbsoluteUrl('uploads/' . $file['filename']);
                            array_push($sub_files, $filename);
                        }
                        $sub_name['subfile']            = $sub_files;
                        array_push($sub, $sub_name);
                    }

                    $userdet['subfolder'] = $sub;
                    array_push($response['details'], $userdet);
                }
                echo json_encode($response);


Answered By - Mohammed Iqbal Khan
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, March 16, 2022

[FIXED] PHP multidimensional array search by value

 March 16, 2022     arrays, multidimensional-array, php     No comments   

Issue

I have an array where I want to search the uid and get the key of the array.

Examples

Assume we have the following 2-dimensional array:

$userdb = array(
    array(
        'uid' => '100',
        'name' => 'Sandra Shush',
        'pic_square' => 'urlof100'
    ),
    array(
        'uid' => '5465',
        'name' => 'Stefanie Mcmohn',
        'pic_square' => 'urlof100'
    ),
    array(
        'uid' => '40489',
        'name' => 'Michael',
        'pic_square' => 'urlof40489'
    )
);

The function call search_by_uid(100) (uid of first user) should return 0.

The function call search_by_uid(40489) should return 2.

I tried making loops, but I want a faster executing code.


Solution

function searchForId($id, $array) {
   foreach ($array as $key => $val) {
       if ($val['uid'] === $id) {
           return $key;
       }
   }
   return null;
}

This will work. You should call it like this:

$id = searchForId('100', $userdb);

It is important to know that if you are using === operator compared types have to be exactly same, in this example you have to search string or just use == instead ===.

Based on angoru answer. In later versions of PHP (>= 5.5.0) you can use one-liner.

$key = array_search('100', array_column($userdb, 'uid'));

Here is documentation: http://php.net/manual/en/function.array-column.php.



Answered By - Jakub Truneček
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, February 28, 2022

[FIXED] Sum all key/value pairs within a multidimensional PHP array

 February 28, 2022     arrays, laravel, multidimensional-array, php     No comments   

Issue

I am developing a small application that pulls recent game data for players, and I want to display a total amount of the stats (goals, assists, plusminus, shots, pim) across all of the games by each player id.

This is an example of what my array looks like for three games that were pulled. The top level is the game id, followed by the player id's that were involved in that game. The layer under each player id are the stats that I want to total up in my output.

Test

I have attempted to loop through each game and player with the following code, but it only appears to pull the non-totaled stats from the first game.

foreach ($results as $result) {
  foreach ($result as $index => $value) {
    $sumArray[$index] = (isset($sumArray[$index]) ? $sumArray[$index] + $value : $value);
  }
}

Would anyone be able offer some guidance on how I can loop through and total up the player stats for each player id occurrence? Any help would be appreciated. Thank you!


Solution

I try to use a more readable variable name

foreach ($results as $game) {
  foreach ($game as $player => $performance) {
    if ( !isset($sumArray[$player] ) {
      $sumArray[$player] = $performance;
    } else {
      foreach ( $performance as $type => $value) {
        $sumArray[$player][$type] += $value;
      }
  }
}


Answered By - Chun
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, January 25, 2022

[FIXED] CakePHP 3 : creating multidimensional cookie

 January 25, 2022     cakephp, cakephp-3.2, cookies, multidimensional-array     No comments   

Issue

I'm working in CakePHP 3.2 and building a shopping cart.

I'm using Cookie component to store the products in the cart.

This is what I'm doing to add products to the cart

public function addToCart()
    {
      $this->loadModel('Products');

      if ($this->request->is('post')) {
        $p_id = $this->request->data('product_id');
        $p_quantity = $this->request->data('qnty');

        $product = $this->Products->get($p_id);

        if (!$product) {
          throw new NotFoundException(__('Invalid Product'));
        }

          $this->Cookie->write('Cart',
            ['id' => $p_id, 'quantity' => $p_quantity]);

          $itemsCount = count($this->Cookie->read('Cart'));

          $this->Flash->success(__('Product added to cart'));
          return $this->redirect($this->referer());

      }
    }

How could I add multidimensional array in Cookie because Cart can have multiple products and each product carry multiple value. Also, How could I print in view of cart() method ?

This is how my cart() method is

public function cart()
    {
      $cart_products = $this->Cookie->read('Cart');

      $this->set('cart_products', $cart_products);
    }

and printing in view as

foreach($cart_products as $c_product):
  echo $c_product->id.' : '.$c_product->quantity;   // line 45
endforeach;

But this gives error as

Trying to get property of non-object [ROOT/plugins/ArgoSystems02/src/Template/Orders/cart.ctp, line 45]

Solution

You write array to cookie:

$this->Cookie->write('Cart', ['id' => $p_id, 'quantity' => $p_quantity]);

I believe what You want is to store all products in cookie:

$cart = $this->Cookie->read('Cart') ? $this->Cookie->read('Cart') : [];
$cart[] = $product;
$this->Cookie->write('Cart', $cart)


Answered By - Bogdan Kuštan
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 22, 2022

[FIXED] How to create a form for a 2D/multi-dimensional table?

 January 22, 2022     cakephp, forms, multidimensional-array     No comments   

Issue

I need to create a form in CakePHP to allow users enter data(numbers) into the cells shown on the table below. The input screen needs look like the table shown below. The users should be able to select any cell they want to enter/update the value, then type in the value, click submit and submit the value/s. Each "Metric section (e.g. Metric A, Metric B..)" will have a submit button so the users can edit/update each section on the table.

 ___________________________ ____________________
|___     ___|___2006_______|__2007____|___2008___|
|_METRIC A__|______________|__________|__________|
| item A1   |          1   |    5     |    7     |
| item A2   |         15   |   18     |   21     |
| item A3   |          3   |    6     |   11     | 
| item A4   |          1   |    1     |    3     |
|___________|______________|__________|__________|
|_METRIC B__|______________|__________|__________|
| item B1   |         12   |   18     |   31     |
| item B2   |          1   |    4     |    6     | 
| item B3   |          0   |    0     |    2     |
--------------------------------------------------

As you can see each metric section is a two dimensional table. So I would like to capture the input data in a 2D array. Currently I have successfully created the display for the data (which was much easier). I simply created an array of metrics, which is an array of 2D arrays. Then I passed that array of 2D arrays to the view file to display the table.

I am kind of lost on how to get the user input for this table. Anyone had any similar experiences? Any suggestion will be greatly helpful to me.


Solution

In case this becomes useful to anyone else, I'm posting my solution here..

I managed to tackle this one by using 'Parallel two dimensional arrays'.

It's a simply trick. You create the 2D array for the display of data. So you have an array for each row in the table. For example if the columns are 'Year 2006', 'Year 2007' & 'Year 2008' like in my question above. You will create a row of data with a value for each year.

$data_for_row_array = array('10', '15', '35');

Like this you create a data array for each row in your table and you will get an array of rows:

$rows_array = array(data_for_row_1_array,  data_for_row_2_array, ..) etc

This will do for the display array.. Now if you want to capture users input for each of those cells in the table all you need to do is create a similar second 2D array with the ids of each data cell taken from the database.. if an id does not exist yet, just leave it blank. And when the user enters data and submits it, just loop through the two 2D arrays and use the ID from one array and the data from the other array to match with it. because in both arrays the matching ID and it's data value will be at the same position. So if you find and ID in the "ids array" and a data value in the same position in the "data array", you just use it to update the database table. This is the concept of 'parallel two dimensional arrays'.

And if you find and empty id value in the IDs array yet some data value at the same position in the data array that means the user has entered a completely new value so you save it as a new data cell in the database.

Hope this gives you some idea.. if it isn't clear just let me know and i will explain it in more detail.



Answered By - Vicer
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to assign data from database to array in laravel controller?

 January 22, 2022     foreach, laravel, laravel-7, multidimensional-array, php     No comments   

Issue

I want to assign data from database to store it in array. I am not getting any error, but only last value getting stored in array.

query to get data from database

 $categories = Category::where('parent_id', '=', null)->where('created_by', '=', \Auth::user()->creatorId())->get();
      
$category = [];
            
           if(count($categories) > 0)
           {
                foreach ($categories as $category) {
                    
                    $category[$category->id] = [
                    'id' => $category->id,
                    'category_name' => $category->name,
                    'SubCategory' => $this->getSubcategoryByIdAction($category->id)
                      
                    ];
                        
                }
           }
           
      

Solution

You overwrite the variable $category in your foreach loop. Try the following code:

<?php

$categories = Category::where('parent_id', '=', null)->where('created_by', '=', \Auth::user()->creatorId())->get();      
$category = [];
            
if(count($categories) > 0)
{
    foreach ($categories as $categoryItem) {
        
        $category[$categoryItem->id] = [
            'id' => $categoryItem->id,
            'category_name' => $categoryItem->name,
            'SubCategory' => $this->getSubcategoryByIdAction($categoryItem->id)  
        ];       
    }
}

var_dump($category);


Answered By - Douma
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to declare 2d matrix array PHP

 January 22, 2022     arrays, matrix, multidimensional-array, php     No comments   

Issue

Here's a piece of PHP code that should declare 2D Array.

$array = array(
    range(1, 4), 
    range(1, 4)
);

print_r($array);

It should look like this:Array

But the output is: Array ( [0] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) [1] => Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) )

So what am I doing wrong? How can I declare\display as a matrix 2d array?


Solution

You adding range only to first 2 indexs.

$array = array(
 range(1, 4), 
 range(1, 4),
 range(1, 4), 
 range(1, 4)
);

If you want better option:

$matrix=  array();

foreach (range(1,4) as $row) {
 foreach (range(1,4) as $col) {
  $matrix[$row][$col] = "some val";
 }
}


print_r($matrix);

For HTML output

<table border="1">
<?php foreach (range(1,4) as $row) { ?>
<tr>
<?php foreach (range(1,4) as $col) { ?>
<td><?php echo $row.$col; ?></td>
<?php  } ?>
</tr>
<?php } ?>
</table>


Answered By - VK321
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, January 16, 2022

[FIXED] Creating Array From Multidimensional Array in cakephp

 January 16, 2022     arrays, cakephp, multidimensional-array, php     No comments   

Issue

In my Cakephp Form I am Selecting Students And multiple documents. My Problem is that I can Create Student Array Fine But Can't able to create the same for uploaded file. i am getting the values in this format

[student_id] => Array
    (
        [0] => 1
        [1] => 2
    )
$student=['1','2'];


$filename= array(
  array(
    "tmp_name" => "C:\xampp\tmp\phpC542.tmp",
    "error" => "0",
    "name" => "file1.pdf",
    "type" => "application/pdf",
    "size" => "410922"
  ),
  array(
    "tmp_name" => "C:\xampp\tmp\phpC562.tmp",
    "error" => "0",
    "name" => "file2.pdf",
    "type" => "application/pdf",
    "size" => "410922"
  ),
  array(
    "tmp_name" => "C:\xampp\tmp\phpC545.tmp",
    "error" => "0",
    "name" => "file3.pdf",
    "type" => "application/pdf",
    "size" => "410922"
  )
);
[filename] => Array
    (
        [0] => Array
            (
                [tmp_name] => C:\xampp\tmp\php53EE.tmp
                [error] => 0
                [name] => file1.pdf
                [type] => application/pdf
                [size] => 403993
            )

        [1] => Array
            (
                [tmp_name] => C:\xampp\tmp\php53FE.tmp
                [error] => 0
                [name] => file2.pdf
                [type] => application/pdf
                [size] => 410922
            )

        [2] => Array
            (
                [tmp_name] => C:\xampp\tmp\php541F.tmp
                [error] => 0
                [name] => file3.pdf
                [type] => application/pdf
                [size] => 846448
            )

    )

I want to create the Array in the following format.

[students] => Array
    (
        [0] => Array
            (
                [student_id] => 1
            )

        [1] => Array
            (
                [student_id] => 2
            )

    )
[files] => Array
    (
        [0] => Array
            (
                [filename] => file1.pdf              
            )
        [1] => Array
            (
                [filename] => file2.pdf              
            )
        [2] => Array
            (
                [filename] => file3.pdf
            )
    )

I am Using the following to get my array. I am successfully getting the results on student array but having problem with generating filename array and saving each file in server. My code is

$data=$this->request->getData();
$studentids=$data['student_id'];
$students=array();
foreach($studentidsas $studentids){
    $key=array('student_id');
    array_push($students,array_fill_keys($key, $studentids));
}
$files=$data['filename'];
$file=array();
foreach($files as $files){
    $key=array('filename');
    array_push($file,array_fill_keys($key, $files));
    move_uploaded_file($data['filename']['tmp_name'],WWW_ROOT.'pdffiles//'.$filename);
}

Any Help will Really Appreciated i am really stuck in this. Thanks.


Solution

array_push($file,array_fill_keys($key, $files['name']));

if you give the field you want to fill your array with, it will work



Answered By - Chiba Andrei
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, December 29, 2021

[FIXED] PHP: Search multidimensional array => get array_keys

 December 29, 2021     arrays, associative-array, multidimensional-array, php     No comments   

Issue

What's the best/fastest way to get the keys of an array by a search of a value in the 2nd level arrays?

$test = array(
    'name_01' => array('yellow', 'red', 'blue', 'black', 'white', 'purple'),
    'name_02' => array('red', 'blue', 'white', 'green'),
    'name_03' => array('blue', 'pink', 'purple', 'blue'),
    'name_04' => array('white', 'black', 'red'),
    'name_05' => array('yellow', 'white', 'pink', 'black')
);

For example the search by pink should return array('name_03', 'name_05')


Solution

A simple foreach() with in_array() is enough

$search = 'pink';

foreach($test as $key=>$arr){
   if(in_array($search,$arr)){
     echo $key.PHP_EOL;
   }

}

Output : https://3v4l.org/HVem8

If you want array as an output : https://3v4l.org/8e0sj



Answered By - Anant Kumar Singh
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing