Manage Php arrays - php

I am new in php.I have learn almost all things in php.I am developing sample application in php. In my application I have two arrays and it looks like:
Array
(
[0] => 1800
[5] => 1500
[6] => 4545
)
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
[6] => g
)
I want output like:
Array
(
[0] => Array
(
[a] => 1800
)
[1] => Array
(
[b] => 0
)
[2] => Array
(
[c] => 0
)
[3] => Array
(
[d] => 0
)
[4] => Array
(
[e] => 0
)
[5] => Array
(
[f] => 1500
)
[6] => Array
(
[g] => 4545
)
)
Please help.

Found solution for your question.
<?php
$arr1 = array(
'0' => '1800',
'5' => '1500',
'6' => '4545'
);
$arr2 = array(
'0' => 'a',
'1' => 'b',
'2' => 'c',
'3' => 'd',
'4' => 'e',
'5' => 'f',
'6' => 'g',
);
$arr3 = array();
foreach($arr2 as $key => $value){
if(!empty($arr1[$key])){
$arr3[$key][$value] = $arr1[$key];
}
else{
$arr3[$key][$value] = 0;
}
}
print '<pre>';
print_r($arr3);
print'</pre>';
?>

$arr1 = array(0 => 1800, 5 => 1500, 6 => 4545,);
$arr2 = array('a', 'b', 'c', 'd', 'e', 'f', 'g',);
$arrNeeded = array();
foreach ($arr2 AS $k => $v) {
$arrNeeded[$k] = array($v => isset($arr1[$k]) ? $arr1[$k] : 0);
}
echo '<pre>' . print_r($arrNeeded, true) . '</pre>';

Please try with below code
$arr1 = array( 0 => 1800 ,5 => 1500 ,6=> 4545 );
$arr2 = array( 0 => 'a' ,1 => 'b', 2=> 'c',3 => 'd' ,4 => 'e' ,5 => 'f' ,6 => 'g' );
$newarr = "";
if(count($arr2) >0){
foreach($arr2 as $key2 => $val2){
$newVal = isset($arr1[$key2])?$arr1[$key2] : 0;
$newarr[$key2] = array($val2 => $newVal);
}
}
echo "<pre>";
print_r($newarr);

This might help you
<?php
$array1 = Array( "0"=>1800,"5" => 1500, "6" => 4545 ) ;
$array2 = Array( "0" => 'a', '1' => 'b', '2' => 'c', '3' => 'd', '4' => 'e', '5' => 'f', '6' => 'g' );
$resultArray = array();
foreach ($array2 as $key2 => $value2 ) {
$found = false;
foreach ($array1 as $key1 => $value1) {
if($key1 == $key2){
$resultArray[$value2] = $value1;
$found = true;
continue;
}
if(!$found)
{
$resultArray[$value2] = 0;
}
}
}
print_r($resultArray);
?>

Related

PHP producing a multidimensional associative array in desired format

I am trying to wrangle data into a desired format. Basically, I have a list in which a subset of the entities can have multiple values and need to be grouped and iterated over within the list.
Given the following example:
$entities = [
0 => ['name' => 'a', 'type' => 'single'],
1 => ['name' => 'b', 'type' => 'single'],
2 => ['name' => 'c', 'type' => 'grouped'],
3 => ['name' => 'd', 'type' => 'grouped'],
4 => ['name' => 'e', 'type' => 'single'],
];
foreach ($entities as $entityKey => $entity) {
if ($entity['type'] == 'single') {
$array[] = ['name' => $entity['name']];
}
if ($entity['type'] == 'grouped') {
// arbitrary number of items
$items = [0 => 'apple', 1 => 'orange', 2 => 'banana'];
foreach ($items as $itemKey => $item) {
$array[] = ['name' => $entity['name']];
}
}
}
print_r($array);
How can I produce output: a, b, c, d, c, d, c, d, e, such that the entities of type 'grouped' are paired and iterated over before he next entity is inserted into the array. Specifically:
Array
(
[0] => Array
(
[name] => a
)
[1] => Array
(
[name] => b
)
[2] => Array
(
[name] => c
)
[3] => Array
(
[name] => d
)
[4] => Array
(
[name] => c
)
[5] => Array
(
[name] => d
)
[6] => Array
(
[name] => c
)
[7] => Array
(
[name] => d
)
[8] => Array
(
[name] => e
)
)
here is a working solution for you.
$entities = [
0 => ['name' => 'a', 'type' => 'single'],
1 => ['name' => 'b', 'type' => 'single'],
2 => ['name' => 'c', 'type' => 'grouped'],
3 => ['name' => 'd', 'type' => 'grouped'],
4 => ['name' => 'e', 'type' => 'single'],
];
$grouped = [];
foreach($entities as $entity){
if($entity['type'] == 'grouped'){
$grouped[] = $entity['name'];
}
}
$f = 0;
foreach ($entities as $entity) {
if ($entity['type'] == 'single') {
$array[] = ['name' => $entity['name']];
}
if ($entity['type'] == 'grouped') {
$items = [0 => 'apple', 1 => 'orange', 2 => 'banana'];
for($i = 0; $i < count($items); $i++) {
foreach($grouped as $grouped_item){
if($f < count($items)*2){
$array[] = ['name' => $grouped_item];
}
$f++;
}
}
}
}
print_r($array);

return array containing duplicates php

i have a multidimensional array and i only want to keep the entries with the most duplicates. the closest i got was:
$wd = array_unique($arr);
$d = array_diff($arr, $wd);
print_r($d);
but that only works for single dimensional arrays and outputs all duplicates. how would i go about doing this?
examples of desired output:
if the array is:
array(
[1] => (
[u] => test1u
[d] => test1d
)
[2] => (
[u] => test2u
[d] => test2d
)
[3] => (
[3] => test3u
[3] => test3d
)
[1] => (
[u] => test1u
[d] => test1d
)
)
it should return array([1] => ( [u] => test1u [d] => test1d))
and if the array is:
array(
[1] => (
[u] => test1u
[d] => test1d
)
[2] => (
[u] => test2u
[d] => test2d
)
[3] => (
[3] => test3u
[3] => test3d
)
[1] => (
[u] => test1u
[d] => test1d
)
[2] => (
[u] => test2u
[d] => test2d
)
)
it should return array([1] => ( [u] => test1u [d] => test1d)[2] => ( [u] => test2u [d] => test2d))
but if the array is:
array(
[1] => (
[u] => test1u
[d] => test1d
)
[2] => (
[u] => test2u
[d] => test2d
)
[3] => (
[3] => test3u
[3] => test3d
)
[1] => (
[u] => test1u
[d] => test1d
)
[2] => (
[u] => test2u
[d] => test2d
)
[1] => (
[u] => test1u
[d] => test1d
)
)
it should only return array([1] => ( [u] => test1u [d] => test1d))
EDIT:
there are duplicate entries in the array because the array came from $arr = json_decode($arr); and the original JSON had duplicate entries.
if there is a better way to do this without decoding the json, let me know.
this is being used as part of a search program. the JSON is an array of all of the entries from the source array that met the criteria for one of the search terms. keeping the entries with the most duplicates insures that those entries contained most if not all of the search terms.
here is the JSON file being decoded:
[{"1":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"roses","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]},{"2":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"roses","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]},{"5":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"roses daffodil","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]},{"3":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"daffodil","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]},{"4":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"daffodil","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]},{"5":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"roses daffodil","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]},{"6":[{"u":"testing","d":"2017\/04\/27","st":"Test","i":"roses daffodil","v":"1","t":"org","sp":"N\/A","k":"0","img":"--"}]}]
in this case the search that made this JSON was for "roses daffodil"
the second example it add – each index just can appear once.
for the first this should work fine:
<?php
$array[] = array( 'u' => 'test1u', 'd' => 'test1d' );
$array[] = array( 'u' => 'test2u', 'd' => 'test2d' );
$array[] = array( '3' => 'test3u', '3' => 'test3d' );
$array[] = array( 'u' => 'test1u', 'd' => 'test1d' );
$array[] = array( 'u' => 'test2u', 'd' => 'test2d' );
var_export( $array );
//echo("\n" . array_count_values($array) . "\n");
foreach( $array as $k => $v ){
foreach( $array as $ke => $ve ){
if( $k == $ke )
continue;
if( $v == $ve ) {
$d[$k]=$v;
unset($array[$k]);
}
}
}
var_export( $d );
?>
unfortunately array_count_values only works for String and int, so it does not work when you have complex values.
First you array cannot have same key. Check the live demo.
<?php
$array[] = array( 'u' => 'test1u', 'd' => 'test1d' );
$array[] = array( 'u' => 'test2u', 'd' => 'test2d' );
$array[] = array( 'u' => 'test3u', 'd' => 'test3d' );
$array[] = array( 'u' => 'test1u', 'd' => 'test1d' );
$array[] = array( 'u' => 'test2u', 'd' => 'test2d' );
$array = array_map(function($v){return implode('-', $v);}, $array);
$count = array_count_values($array);
print_r($count);
arsort($count);
$max = current($count);
while(current($count) == $max)
{
$arr = explode('-', key($count));
$result[] = array('u' => $arr[0], 'd' => $arr[1]);
next($count);
}
print_r($result);
i have found the solution! bit long winded but it works!
$json = json_decode($json);
$jsonoutc = $jsonout = "";
$arrid = $arrout = $disp = array();
foreach ($json as $null => $arr){
foreach ($arr as $key => $null){
$arrid[] = $key;
}
}
$vals = array_count_values($arrid);
foreach ($vals as $val => $counted){
if ($counted > $jsonoutc){
$jsonoutc = $counted;
}
}
foreach ($vals as $val => $counted){
if ($counted == $jsonoutc){
$arrout[] = $val;
}
}
foreach ($arrout as $null => $val){
foreach ($json as $null => $arr){
foreach ($arr as $key => $list){
if ($key == $val){
$disp[$key] = $list;
}
}
}
}
print_r($disp);

Access multidimensional associative array using integer index

Assuming I have an associative array which looks like this:
$arr = array(
'a' => array(
'b' => 'b',
'c' => 'c',
'd' => array(
'e' =>'e'
),
'f' => 'f',
'g' => 'g'
),
'h' => 'h',
'i' => array(
'j' => 'j',
'k' => 'k'
)
);
Now I want to access array elements using integer-index:
0 will return array of key 'a'
1 will return array of key 'b'
2 will return array of key 'c'
3 will return array of key 'd'
4 will return array of key 'e'
..
11 will return array of key 'k'
I have tried to accomplish this by recursion using the following code:
function getElement($arr, $id)
{
static $counter = 0;
foreach($arr as $key => $val){
$varNum = count($val);
$total = $counter + $varNum;
if($counter == $id){
return $val;
}
elseif($total > $id){
$counter++;
$res = getElement($val, $id);
return $res;
}
$counter++;
}
}
However from index 4 the function fails.
any suggestions?
Using array_walk_recursive:
$list = [];
array_walk_recursive($arr, function($value) use (&$list) {
$list[] = $value;
});
print_r($list);
Will return something like:
Array
(
[0] => b
[1] => c
[2] => e
[3] => f
[4] => g
[5] => h
[6] => j
[7] => k
)
now to return a full list of keys , you may use the following function:
function walk_recursive($arr, &$list = [])
{
foreach ($arr as $k => $ar) {
if (is_array($ar)) {
$list[] = $k;
walk_recursive($ar, $list);
} else {
$list[] = $ar;
}
}
return $list;
}
print_r(walk_recursive($arr));
this output the following :
Array
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
[6] => g
[7] => h
[8] => i
[9] => j
[10] => k
)
live example: https://3v4l.org/Wv0nL

Converting table-like array to a tree-like array

Consider the following example:
function tableToTree($array, $parents)
{
$result = [];
$p = $parents;
foreach ($array as $k => $row) {
$result[$row[$p[0]]][$row[$p[1]]]= $row[$p[2]]; // **
}
return $result;
}
$foo = [
['x' => 'a', 'y' => 'n','z'=>'AA'],
['x' => 'a', 'y' => 'm','z'=>'BB'],
['x' => 'b', 'y' => 'v','z'=>'CC'],
['x' => 'b', 'y' => 'w','z'=>'DD'],
];
print_r(tableToTree($foo, ['x', 'y','z']));
Which yields:
Array
(
[a] => Array
(
[n] => AA
[m] => BB
)
[b] => Array
(
[v] => CC
[w] => DD
)
)
The above code only works when there are only two parents. How to rewrite the line denoted by ** in a way that it work with arbitrary number of parents.
function tableToTree($array, $parent)
{
$result = array();
foreach ($array as $row) {
$r = &$result; // pointer to result
$p = $parent; // temporary copy of parents
while(count($p) > 2) { // until last key and value
$i = array_shift($p); // next key
if(!isset($r[$row[$i]])) $r[$row[$i]] = null; // add level
$r = &$r[$row[$i]]; // shift pointer to new level
}
$r[$row[array_shift($p)]] = $row[array_shift($p)]; // set value
}
return $result;
}
$foo = array(
array('N' => 2, 'x' => 'a', 'y' => 'n','z'=>'AA'),
array('N' => 1, 'x' => 'a', 'y' => 'm','z'=>'BB'),
array('N' => 2, 'x' => 'b', 'y' => 'v','z'=>'CC'),
array('N' => 1, 'x' => 'b', 'y' => 'w','z'=>'DD'),
array('N' => 1, 'x' => 'c', 'y' => 'w','z'=>'DD'));
print_r(tableToTree($foo, array('N','x', 'y','z')));
result
array (
2 => array (
'a' => array ( 'n' => 'AA',),
'b' => array ( 'v' => 'CC',),
),
1 => array (
'a' => array ( 'm' => 'BB', ),
'b' => array ( 'w' => 'DD', ),
'c' => array ( 'w' => 'DD', ),
),
)

Php Multidimensional Array

I have below multidimensional array
$testarray=Array
(
1 => Array
(
0 => 'A',
1 => 'B'
),
2 => Array
(
0 => 'A',
1 => 'C'
),
3 => Array
(
0 => 'A',
1 => 'C',
2 => 'D'
),
4 => Array
(
0 => 'A',
1 => 'C',
2 => 'E'
),
5 => Array
(
0 => 'X',
1 => 'Y'
),
6 => Array
(
0 => 'X',
1 => 'Y',
2 => 'Z'
),
7 => Array
(
0 => 'X',
1 => 'Y',
2 => 'ZZ'
),
8 => Array
(
0 => 'P',
1 => 'Q'
),
9 => Array
(
0 => 'P',
1 => 'Q',
2 => 'R'
),
10 => Array
(
0 => 'P',
1 => 'Q',
2 => 'R',
3 => 'S'
)
);
I need to generate below array using $testarray (aultidimentional array):
array(A=array(B, C=array(D,E)),
X=array(Y=>array(Z,ZZ)),
P=array(Q=>array(R=>array(S))
At least in the version of PHP I use you can do something like
$testArray = Array(
1 => Array(
'A'=> Array(
//Value of A here
)
'B' => Array(
//Value of B here
)
);
To access them you can write
$testArray[1]['A'];
If you can change the value of $testArray this should help.
This should work. Any refinements (and explanations) would be appreciated.
foreach( $testarray as $values ) {
$depth = count($values);
$ref =& $array;
for( $i=0; $i<$depth; $i++ ) {
if( $i == $depth-1 ) {
$ref[] = $values[$i];
}
else {
if( !is_array( $ref ) || !array_key_exists( $values[$i], $ref ) ) {
$ref[$values[$i]] = array();
}
if( ( $key = array_search( $values[$i], $ref ) ) !== FALSE ) {
unset( $ref[$key] );
}
$ref =& $ref[$values[$i]];
}
}
}
Output:
array
'A' =>
array
0 => string 'B' (length=1)
'C' =>
array
0 => string 'D' (length=1)
1 => string 'E' (length=1)
'X' =>
array
'Y' =>
array
0 => string 'Z' (length=1)
1 => string 'ZZ' (length=2)
'P' =>
array
'Q' =>
array
'R' =>
array
0 => string 'S' (length=1)

Categories