I am able to traverse a multi-dimensional array, but I also need information about dependencies. Here is what I am trying to do. I have an array like this:
array(
'top1' => 'sth',
'top2' => array(
'sub1' => 'sth',
'sub2' => array(
'line1' => 'sth',
'line2' => 'sth'
)
)
'top3' => 'sth'
)
I am able to traverse the array to get all the keys, result is this:
array([0] => 'top1', [1] => 'top2', [2] => 'sub1', [3] => 'sub2', ...)
However, I need to know the parent of the current element. So I hope I could get something like this:
array(
[top1] => array('parent' => 0, 'id' => 1),
[top2] => array('parent' => 0, 'id' => 2),
[sub1] => array('parent' => 2, 'id' => 2.1),
[sub2] => array('parent' => 2, 'id' => 2.2),
[line1] => array('parent' => 2.2, 'id' => 2.2.1),
...
[top3] => array('parent' => 0, 'id' => 3)
)
I have been trying many ways, but couldn't always get the correct result. Can anyone solve this out? Thanks!
here is a working example for you
function traverse(array $input, $parent = null) {
$result = array();
$current = 1;
foreach ($input as $key => $value) {
$id = null !== $parent ? $parent . '.' . $current : $current;
$result[$key] = array('parent' => null !== $parent ? $parent : 0, 'id' => $id);
if (is_array($value)) {
$result = array_merge($result, traverse($value, $id));
}
$current++;
}
return $result;
}
$input = array(
'top1' => 'sth',
'top2' => array(
'sub1' => 'sth',
'sub2' => array(
'line1' => 'sth',
'line2' => 'sth'
)
),
'top3' => 'sth'
);
echo '<pre>';
print_r($input);
echo '<hr>';
print_r(traverse($input));
echo '</pre>';
Related
Thank you in advance. Is there any way to create a multidimensional array from key names.
$array = array(
'brand/name' => 'BRAND_NAME',
'brand/model' => 'MODEL_NO',
'brand/inv/qty' => '20',
'brand/inv/cost' => '30',
'wh' => 'NY',
'brand/inv/sales' => '40'
);
Transform to this array.
$array = array(
'brand' => array(
'name' => 'BRAND_NAME',
'model' => 'MODEL_NO',
'inv' => array(
'qty' => 20,
'cost' => 30,
'sales' => 40,
)
),
'wh' => 'NY'
);
Thank you !
Try my code (I used the reference operator "&" to get the successive inner arrays):
Input array:
$array = array(
'brand/name' => 'BRAND_NAME',
'brand/model' => 'MODEL_NO',
'brand/inv/qty' => '20',
'brand/inv/cost' => '30',
'wh' => 'NY',
'brand/inv/sales' => '40'
);
php code:
<?php
$resultArray = array();
foreach($array as $path => $element) {
$pathArray = explode("/", $path);
$auxRef = &$resultArray;
foreach($pathArray as $pathPart) {
if(! array_key_exists($pathPart, $auxRef)) {
$auxRef[$pathPart] = array();
}
$auxRef = &$auxRef[$pathPart];
}
$auxRef = $element;
unset($auxRef);
}
?>
Result array:
array ( 'brand' => array ( 'name' => 'BRAND_NAME', 'model' => 'MODEL_NO', 'inv' => array ( 'qty' => '20', 'cost' => '30', 'sales' => '40', ), ), 'wh' => 'NY', )
//codeigniter array passed form controller to view
$data['combined_array'] = array('75x35' => $output,'20x5' => $output1);
$all_dates = Array ('2019-11-19','2019-11-20', '2019-11-21','2019-11-22' );
foreach($combined_array as $key => $value){
foreach($value as $key1 => $value1)
{
foreach($value1 as $key2 => $value2)
{
if($value2['size'] == '20x5'){
if(in_array($value2['date'], $all_dates))
{
echo "exists -".$value2['date'];
}
else
{
echo "doesnt exists -".$value2['date'];
}
}
}
}
}
$value2['date'] contains the values 2019-11-20, 2019-11-21,2019-11-22. i want to check if all the values in all_dates exists in $value2['date']. if not then echo doesn't exists. but my code doesn't work.
var_export($combined_array)
array ( '75x35' => array ( '2019-11-19' => array ( 0 => array ( 'size' => '75x35', 'category' => 'steel', 'type' => 'structural', 'sub_type' => 'flats', 'date' => '2019-11-19', 'stock_out' => '4', ), ), '2019-11-20' => array ( 0 => array ( 'size' => '75x35', 'category' => 'steel', 'type' => 'structural', 'sub_type' => 'flats', 'date' => '2019-11-20', 'stock_out' => '6', ), ), '2019-11-21' => array ( 0 => array ( 'size' => '75x35', 'category' => 'steel', 'type' => 'structural', 'sub_type' => 'flats', 'date' => '2019-11-21', 'stock_out' => '5', ), ), '2019-11-22' => array ( 0 => array ( 'size' => '75x35', 'category' => 'steel', 'type' => 'structural', 'sub_type' => 'flats', 'date' => '2019-11-22', 'stock_out' => '5', ), ), ), '20x5' => array ( '2019-11-20' => array ( 0 => array ( 'size' => '20x5', 'category' => 'steel', 'type' => 'structural', 'sub_type' => 'flats', 'date' => '2019-11-20', 'stock_out' => '2', ), ), '2019-11-21' => array ( 0 => array ( 'size' => '20x5', 'category' => 'steel', 'type' => 'structural', 'sub_type' => 'flats', 'date' => '2019-11-21', 'stock_out' => '1', ), ), '2019-11-22' => array ( 0 => array ( 'size' => '20x5', 'category' => 'steel', 'type' => 'structural', 'sub_type' => 'flats', 'date' => '2019-11-22', 'stock_out' => '3', ), ), ), )
For checking each date value of each size row replace your if statement with a new one:
$temp = [];
foreach($combined_array as $key => $value){
foreach($value as $key1 => $value1)
{
foreach($value1 as $key2 => $value2)
{
//if($value2['size'] == '20x5'){
if (!in_array($value2['date'],$temp)){
$temp[] = $value2['date'];
if(in_array($value2['date'], $all_dates))
{
echo "exists -".$value2['date'];
echo "\r\n";
}
else
{
echo "doesnt exists -".$value2['date'];
echo "\r\n";
}
}
}
}
}
EDITED:
Or you can check all_dates values on existing inside defined size:
$temp = [];
foreach($combined_array as $key => $value){
if($key == '20x5') {
$temp = array_keys($value);
$diff = array_diff($all_dates, $temp);
foreach($all_dates as $date)
{
echo !in_array($date, $diff) ? "exists -".$date.PHP_EOL : "doesnt exists -".$date.PHP_EOL;
}
}
}
Demo
A simple solution is for each part of the combined array is to check the difference between the list of dates ( the keys ) and the list of dates you want. This can be done using array_keys() to get a list of the dates and array_diff() to check for missing dates...
foreach( $combined_array as $key => $value){
$dateMismatch = array_diff($all_dates, array_keys($value));
if(count($dateMismatch) > 0 ){
echo "Dates for {$key} missing=".implode(",", $dateMismatch).PHP_EOL;
}
}
This just displays the differences as...
Dates for 20x5 missing=2019-11-19
for your test data.
EDIT:
If you just want the dates different for 1 size, then you don't need a loop, just pick out the details first using something like $combined_array['20x5']...
$dateMismatch = array_diff($all_dates, array_keys($combined_array['20x5']));
if(count($dateMismatch) > 0 ){
echo "Dates missing=".implode(",", $dateMismatch).PHP_EOL;
}
I've been trying to organize data into a multidimensional array from a foreach loop but the data is all over the place.
This is what I coded:
$productIDs = array(
'0' => array(
'product_id' => '10',
'product_name' => 'Test',
'product_file' => 'file10',
'product_image' => 'https://i.imgur.com/dXb6.png',
),
'1' => array(
'product_id' => '20',
'product_name' => 'Test1',
'product_file' => 'file20',
'product_image' => 'https://i.imgur.com/MuP8.png',
),
'2' => array(
'product_id' => '30',
'product_name' => 'No product',
'product_file' => 'file30',
'product_image' => 'https://i.imgur.com/kWP3.png',
)
);
$urlIDs = array(10,20);
function getFiles($productIDs, $urlIDs)
{
foreach($productIDs as $ids)
{
foreach($urlIDs as $products)
{
if(in_array($products, $ids)){
$data1[] = $ids['product_id'];
$data2[] = $ids['product_file'];
$data3[] = $ids['product_image'];
}
}
}
return array($data1, $data2, $data3);
}
$getFiles = getFiles($productIDs, $urlIDs);
And the output for the following is:
Array
(
[0] => Array
(
[0] => 10
[1] => 20
)
[1] => Array
(
[0] => file10
[1] => file20
)
[2] => Array
(
[0] => https://i.imgur.com/dXb6.png
[1] => https://i.imgur.com/MuP8.png
)
)
Although what I'm trying to accomplish is:
Array
(
[0] => Array
(
[id] => 10
[file] => file10
[image] => https://i.imgur.com/dXb6.png
)
[1] => Array
(
[id] => 20
[file] => file20
[image] => https://i.imgur.com/MuP8.png
)
)
I tried the following:
function getFiles($productIDs, $urlIDs)
{
foreach($productIDs as $ids)
{
foreach($urlIDs as $products)
{
if(in_array($products, $ids)){
$data['id'] = $ids['product_id'];
$data['file'] = $ids['product_file'];
$data['image'] = $ids['product_image'];
}
}
}
return array($data);
}
Which returns the following without looping through all id's, it should return both arrays since both id's are matching.
Array
(
[0] => Array
(
[id] => 20
[file] => file20
[image] => https://i.imgur.com/MuP8.png
)
)
You could say the first batch of code without the specific key names isn't what I want, but I just wanted to show what I had tried. The last batch works (with key names), but doesn't loop through all of the $urlIDs, and for some reason that I can't understand, the code isn't even returning id = 10, it's returning id = 20, though it's second in the array. If someone could explain why this is happening I'd appreciate it.
In case it's useful: https://eval.in/764083
PHP code demo
<?php
$productIDs = array(
'0' => array(
'product_id' => '10',
'product_name' => 'Test',
'product_file' => 'file10',
'product_image' => 'https://i.imgur.com/dXb6.png',
),
'1' => array(
'product_id' => '20',
'product_name' => 'Test1',
'product_file' => 'file20',
'product_image' => 'https://i.imgur.com/MuP8.png',
),
'2' => array(
'product_id' => '30',
'product_name' => 'No product',
'product_file' => 'file30',
'product_image' => 'https://i.imgur.com/kWP3.png',
)
);
$urlIDs = array(10,20);
function getFiles($productIDs, $urlIDs)
{
$result=array();
foreach($productIDs as $key => $productData)
{
if(!in_array($productData['product_id'],$urlIDs))
{
unset($productIDs[$key]);
}
else
{
$result[]=array("id"=>$productData['product_id'],"file"=>$productData['product_file'],"image"=>$productData['product_image']);
}
}
return $result;
}
$getFiles = getFiles($productIDs, $urlIDs);
print_r($getFiles);
Output:
Array
(
[0] => Array
(
[id] => 10
[file] => file10
[image] => https://i.imgur.com/dXb6.png
)
[1] => Array
(
[id] => 20
[file] => file20
[image] => https://i.imgur.com/MuP8.png
)
)
Leveraging your tried out solution, change your tried solution to this.
function getFiles($productIDs, $urlIDs)
{
foreach($productIDs as $ids)
{
foreach($urlIDs as $products)
{
if(in_array($products, $ids)){
$data[] = [ "id" => $ids['product_id'],
"file" => $ids['product_file'],
"image" => $ids['product_image']];
}
}
}
return $data;
}
Try this one.
function getFiles($productIDs, $urlIDs)
{
$newDara = [];
foreach($productIDs as $ids)
{
foreach($urlIDs as $products)
{
if(in_array($products, $ids)){
$data['id'] = $ids['product_id'];
$data['file'] = $ids['product_file'];
$data['image'] = $ids['product_image'];
$newData[] = $data;
}
}
}
return array($newData);
}
Try this version
<?php
/**
* Created by PhpStorm.
* User: lenovo
* Date: 3/30/2017
* Time: 5:53 AM
*/
$productIDs = array(
'0' => array(
'product_id' => '10',
'product_name' => 'Test',
'product_file' => 'file10',
'product_image' => 'https://i.imgur.com/dXb6.png',
),
'1' => array(
'product_id' => '20',
'product_name' => 'Test1',
'product_file' => 'file20',
'product_image' => 'https://i.imgur.com/MuP8.png',
),
'2' => array(
'product_id' => '30',
'product_name' => 'No product',
'product_file' => 'file30',
'product_image' => 'https://i.imgur.com/kWP3.png',
)
);
$urlIDs = array(10,20);
$ouput = [];
foreach($productIDs as $product){
if(in_array($product['product_id'],$urlIDs)){
$ouput[] = array("id"=>$product["product_id"], "file"=>$product["product_file"], "image"=>$product["product_image"]);
}
}
echo "<pre>";
print_r($ouput);
echo "</pre>";
Check the
Good Luck
The other answers are either doing too many loops, or looping through the $productIDs array (which I assume is much longer in your actual project).
This method will only iterate on your search array, this should provide a performance boost. You will see this approach posted as the top comment # http://php.net/manual/en/function.array-search.php
Code: (Demo)
$productIDs = array(
'0' => array(
'product_id' => '10',
'product_name' => 'Test',
'product_file' => 'file10',
'product_image' => 'https://i.imgur.com/dXb6.png',
),
'1' => array(
'product_id' => '20',
'product_name' => 'Test1',
'product_file' => 'file20',
'product_image' => 'https://i.imgur.com/MuP8.png',
),
'2' => array(
'product_id' => '30',
'product_name' => 'No product',
'product_file' => 'file30',
'product_image' => 'https://i.imgur.com/kWP3.png',
)
);
$urlIDs=array(10,20);
foreach($urlIDs as $prd_id){
if(($i=array_search($prd_id,array_column($productIDs,'product_id')))!==false){
$result[]=['id'=>$productIDs[$i]['product_id'],
'file'=>$productIDs[$i]['product_file'],
'image'=>$productIDs[$i]['product_image']
];
}else{
echo "$prd_id not found";
}
}
var_export($result);
Output:
array (
0 =>
array (
'id' => '10',
'file' => 'file10',
'image' => 'https://i.imgur.com/dXb6.png',
),
1 =>
array (
'id' => '20',
'file' => 'file20',
'image' => 'https://i.imgur.com/MuP8.png',
),
)
I have an array of data like this . This array is the result of a database query , I want to get the index of rows and columns . I tried to get the index of each row but nonetheless failed. so, can anyone help me?
Query Result
array(
(int) 0 => array(
'B' => array(
'company' => 'ABC'
),
'User' => array(
'company' => 'abc'
),
(int) 0 => array(
'date_part' => '3',
'jumlah' => null,
'jumbuy' => '50990',
'admin' => '50010'
),
(int) 1 => array(
'date_part' => '4',
'jumlah' => null,
'jumbuy' => '98990',
'admin' => '2010'
)
),
(int) 1 => array(
'B' => array(
'company' => 'BCD'
),
'User' => array(
'company' => 'bcd'
),
(int) 0 => array(
'date_part' => '3',
'jumlah' => null,
'jumbuy' => '65000',
'admin' => '5000'
),
(int) 1 => array(
'date_part' => '4',
'jumlah' => null,
'jumbuy' => '9000',
'admin' => '5000'
)
),
(int) 3 => array(
'B' => array(
'company' => 'CDE'
),
'User' => array(
'company' => 'cde'
),
(int) 0 => array(
'date_part' => '4',
'jumlah' => null,
'jumbuy' => '34566',
'admin' => '2010'
)
)
);
Get Index
for ($row = 0; $row < count($array); $row++) {
for($col = 0; $col < count(.....); $col++ ) {
echo "Baris [row] kolom [colum]"; // output row and column
}
}
The below code will give you all the indexes of this given array.
I checked the given array with the following code in my localhost.
And it gives us all the keys and the values in this array.
Try this
<?php
foreach($array as $arr=>$value )
{
foreach($value as $ar=>$a)
{
echo $ar."<br>";
foreach($a as $res =>$r)
{
echo $res.": ";
echo $r;
echo "<br>";
}
}
}
?>
Use nested foreach for echoes keys:
foreach ($array as $row => $v) {
foreach ($v as $col => $val) {
echo 'row: ' . $row . ', col: ' . $col . '<br>';
}
}
use the following
foreach ($values as $inde => $value) {
foreach ($value as $key => $result) {
echo '['. $inde.'] ---' .$key . '<br>';
}
}
output will be
[0] ---B
[0] ---User
[0] ---0
[0] ---1
[1] ---B
[1] ---User
[1] ---0
[1] ---1
[3] ---B
[3] ---User
[3] ---0
Let's say i have an array like this:
$array = array(
0 =>
array (
'value' => '1' ,
'name' => 'dasdfa sadfa' ),
1=> Array (
'value' => 'adresa#gmail.com' ,
'name' => 'd2' ),
21 =>
array(
'value' => 'adresa#gmail.com' ,
'name' => 'name1`' ),
23 =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
24 =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
26 =>
array(
'value' => 'ricardo.ramos#amadeus.com',
'name' => '43414 Test01'),
27 =>
array(
'value' => 'sta3no213123ct3av#yahoo.com',
'name' => 'oct oct' )
);
I want to know if exists duplicated value in array with key 'value' I know how to do this if i want a specified value but general no. The result must be an array with no duplicated values(eg:
$array = array(
0 =>
array (
'value' => '1' ,
'name' => 'dasdfa sadfa' ),
1=> Array (
'value' => 'adresa#gmail.com' ,
'name' => 'd2' ),
23 =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
26 =>
array(
'value' => 'ricardo.ramos#amadeus.com',
'name' => '43414 Test01'),
27 =>
array(
'value' => 'sta3no213123ct3av#yahoo.com',
'name' => 'oct oct' )
);`
Please help me.
This is my try
function has_dupes($array){
$dupe_array = array();
foreach($array as $val){
if(++$dupe_array[$val] > 1){
return true;
}
}
return false;
}
Try this way:
$array = array(
'0' =>
array (
'value' => '1' ,
'name' => 'dasdfa sadfa' ),
'1'=> Array (
'value' => 'adresa#gmail.com' ,
'name' => 'd2' ),
'21' =>
array(
'value' => 'adresa#gmail.com' ,
'name' => 'name1`' ),
'23' =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
'24' =>
array(
'value' => 'popescu.catalina#gmail.com' ,
'name' => 'POPESCU CATALINA' ),
'26' =>
array(
'value' => 'ricardo.ramos#amadeus.com',
'name' => '43414 Test01'),
'27' =>
array(
'value' => 'sta3no213123ct3av#yahoo.com',
'name' => 'oct oct' )
);
$array = array_map("unserialize", array_unique(array_map("serialize", $array)));
$result = array_unique($array);
print_r($result);
And if you want to store all unique data in one array do it like this:
//declare $array
$unique_array = array();
foreach ($array as $key => $type) {
foreach($type as $vale => $name) {
if ($vale == 'value') {
//echo $name . '<br>';
array_push($unique_array, $name);
}
}
}
$result = array_unique($unique_array);
foreach ($result as $res) {
echo $res . '<br>';
}
Try this
$values = array_map("unserialize", array_unique(array_map("serialize", $array)));
foreach ($values as $key => $value)
{
if ( is_array($value) )
{
$values[$key] = $value;
}
}
print_r($values);
$unique_data = array(); // the result array
$duplicate_data = array();
$seen = array();
foreach ($array as $key => $arr) {
$value = $arr['value'];
if (!isset($seen[$value])) {
$seen[$value] = '';
$unique_data[$key] = $arr;
} else {
$duplicate_data[$key] = $arr; // optional
}
}
unset($seen); // optional in function scope