Assign number as array key name - php

I need to assign in an associative array a number as key name, but if I do:
// Places (generated by mysql)
$places = array (
0 => '1234',
1 => '2345'
);
// Week stats (generated by mysql)
$week = array (
1234 =>
array (
0 =>
array (
'iid' => '1234',
'mid' => 'xxxxxxxx',
'name' => 'Name1',
),
1 =>
array (
'iid' => '1234',
'mid' => 'xxxxxxxx',
'name' => 'Name3',
)
),
2345 =>
array (
0 =>
array (
'iid' => '2345',
'mid' => 'xxxxxxxx',
'name' => 'Name2',
),
2 =>
array (
'iid' => '2345',
'mid' => 'xxxxxxxx',
'name' => 'Name4',
)
)
);
foreach($places as &$place) {
echo $place;
$i = 0;
foreach($week[$i] as &$value) {
echo $value["name"];
$i++;
}
}
it doesn't work:
http://codepad.viper-7.com/Y1g37t
because seems I should call it with:
echo $arr[<specific index>];
Instead I need to set "1234" and "2345" as strings, like this array:
$arr = Array("foo" => "bar");
So I can call it with
$arr[0] // bar
How can I do?
Solution
Thanks to #kirilloid
i use this code:
$vararr = array_keys($week);
$key = $vararr[$i];
To get the key

It because it's an map and map associates values to keys so you have to do this :
<?php
$myNumber = 1234;
$myValue = "foo";
$arr = Array( $myNumber => $myValue );
echo $arr[1234];
?>
And don't forget to replace the ":" at your first line !
To iterate on a "map" you can use the foreach function :
foreach($arr as $key=>$value) {
echo $key;
echo $value;
}
This should display your key and the value associated :
1234
foo
Here is the difference with a simple array:
$array = array("foo", "bar", "hallo", "world");
echo $array[0];

You may either use array_keys:
echo $arr[array_keys($arr)[0]];
or reset and current:
reset($arr);
echo current($arr);

There is no problem here - this is how it is supposed to work.
If you create an array like this:
$myNumber = 1234;
$myValue = "foo";
$arr = Array( $myNumber => $myValue );
then the index of the element is 1234, not 0.
You can retrieve it with echo $arr[1234]
If you need to loop over the array you can do so with
foreach($arr as $key=>$value) {
// do something with $value
}

There is no problem. As the value of $myNumber is 1234, you should access the array element like this:
echo $arr[1234];
If you need to access them in a foor loop you can get the keys as an array:
$keys = array_keys($arr);
$keys_count = count($keys);
for ($i=0; i<$keys_count; $i++) {
echo $arr[$keys[$i]];
}

Related

How to show duplicate data in multidimensional array using PHP

I am using Spout Excel reader to read Excel files from php code and saving into a multidimensional array in PHP variable,Array looks like this
$array = [
[
'id[0]' => 'BX-78',
'Name[0]' => 'XXX',
'Address[0]' => 'YUUSATD'
],
[
'id[1]' => 'BX-79',
'Name[1]' => 'YYY',
'Address[1]' => 'DHJSHDJGY'
],
[
'id[2]' => 'BX-80',
'Name[2]' => 'ZZZ',
'Address[2]' => 'DDSDSDA'
]
[
'id[3]' => 'BX-78',
'Name[3]' => 'AAA',
'Address[3]' => 'FSDSDS'
][
'id[4]' => 'BX-81',
'Name[4]' => 'XXX',
'Address[4]' => 'DSDSDSD'
]];
Now i want to show duplicate data from above array using two keys ['id'] and ['name'] if id repeats show as duplicate data,
If name repeats show that row as duplicate data if both are duplicate show as again duplicate row
Otherwise it is unique row.
I have tried using multidimensional array sorting but it is using only one key to match data in rows.
foreach ($arrExcelData as $v) {
if (isset($arrExcelData[$v[0]])) {
// found duplicate
continue;
}
// remember unique item
$arrExcelData3[$v[0]] = $v;
}
// if you need a zero-based array, otheriwse work with $_data
$arrExcelData2 = array_values($arrExcelData3);
Edited : Expected Output Result :
Matching Rows:
Id Name Address
-------------------------
BX-78 XXX YUUSATD
BX-78 AAA DDSDSDA
BX-81 XXX DSDSDSD`
If you want to list the duplicate values, I think the address of the second match should be FSDSDS as there is not item with name AAA and value DDSDSDA:
BX-78 AAA FSDSDS
If that is the case, what you could do is to first use a double foreach to mark the arrays that contain a duplicate id or name by for example adding a property named id and name except when the array is itself in the second loop.
After this loop, you can tell which arrays are the duplicate ones. Instead of using a corresponding index 0 as in id[0], I have used reset and next so it is not tied to these indexes.
To get the filtered result you could use array_reduce to check for the array keys and unset them.
For example:
foreach ($array as $index => $a) {
foreach ($array as $v) {
if ($v === $a) continue;
if (reset($v) === reset($a)) $array[$index]["id"] = "duplicate";
if (next($v) === next($a)) $array[$index]["name"] = "duplicate";
}
}
$array = array_reduce($array, function($carry, $item) {
if (array_key_exists("id", $item) || array_key_exists("name", $item)) {
unset($item["id"], $item["name"]);
$carry[] = $item;
}
return $carry;
}, []);
print_r($array);
Result
Array
(
[0] => Array
(
[id[0]] => BX-78
[Name[0]] => XXX
[Address[0]] => YUUSATD
)
[1] => Array
(
[id[3]] => BX-78
[Name[3]] => AAA
[Address[3]] => FSDSDS
)
[2] => Array
(
[id[4]] => BX-81
[Name[4]] => XXX
[Address[4]] => DSDSDSD
)
)
See a php demo
I've this very pragmatic approach:
$spout_output = [
[
'id[0]' => 'BX-78',
'Name[0]' => 'XXX',
'Address[0]' => 'YUUSATD'
],
[
'id[1]' => 'BX-79',
'Name[1]' => 'YYY',
'Address[1]' => 'DHJSHDJGY'
],
[
'id[2]' => 'BX-80',
'Name[2]' => 'ZZZ',
'Address[2]' => 'DDSDSDA'
],
[
'id[3]' => 'BX-78',
'Name[3]' => 'AAA',
'Address[3]' => 'FSDSDS'
],
[
'id[4]' => 'BX-81',
'Name[4]' => 'XXX',
'Address[4]' => 'DSDSDSD'
]];
// store id to row, and name to row mappings.
// id and name will be keys, value will be an array of indexes of the array $spout_output
$id_to_rows = array();
$name_to_rows = array();
$duplicate_ids = array();
$duplicate_names = array();
foreach($spout_output as $row => $data)
{
$key_id = 'id['.$row.']';
$key_name = 'Name['.$row.']';
if(!isset($data[$key_id]))
continue;
$value_id = $data[$key_id];
$value_name = $data[$key_name];
if(!isset($id_to_rows[$value_id]))
{
$id_to_rows[$value_id] = array();
}
else
{
if(!isset($duplicate_ids[$value_id]))
{
$duplicate_ids[$value_id] = $id_to_rows[$value_id];
}
$duplicate_ids[$value_id][] = $row;
}
if(!isset($name_to_rows[$value_name]))
{
$name_to_rows[$value_name] = array();
}
else
{
if(!isset($duplicate_names[$value_name]))
{
$duplicate_names[$value_name] = $name_to_rows[$value_name];
}
$duplicate_names[$value_name][] = $row;
}
$id_to_rows[$value_id][] = $row;
$name_to_rows[$value_name][] = $row;
}
echo 'Duplicates:';
echo '<br>';
$shown_rows = array();
foreach($duplicate_ids as $id => $rows)
{
foreach($rows as $nr)
{
echo $id . '|' . $spout_output[$nr]['Name['.$nr.']'] . '|' . $spout_output[$nr]['Address['.$nr.']'];
echo '<br>';
$shown_rows[] = $nr;
}
}
foreach($duplicate_names as $name => $rows)
{
foreach($rows as $nr)
{
// if already shown above, skip this row
if(in_array($nr, $shown_rows))
continue;
echo $spout_output[$nr]['id['.$nr.']'] . '|' . $spout_output[$nr]['Name['.$nr.']'] . '|' . $spout_output[$nr]['Address['.$nr.']'];
echo '<br>';
$shown_rows[] = $nr;
}
}
Outputs:
Duplicates:
BX-78|XXX|YUUSATD
BX-78|AAA|FSDSDS
BX-81|XXX|DSDSDSD
I think your 'wanted output' contains an error in the address?
Anyway, with my code above I think you'll have enough mapped data to produce the output you want.
You could do something like this:
$dupes = [];
$current = [];
foreach ($array as $index => $entry) {
$idKey = "id[$index]";
$nameKey = "Name[$index]";
if (array_key_exists($entry[$idKey], $current)) {
$dupes[] = [$entry, $current[$entry[$idKey]]];
}
elseif (array_key_exists($entry[$nameKey], $current)) {
$dupes[] = [$entry, $current[$entry[$nameKey]]];
}
else {
$current[$entry[$idKey]] = $current[$entry[$nameKey]] = $entry;
}
}
print_r($dupes);
Which results in an array containing each set of duplicates (array of arrays):
Array
(
[0] => Array
(
[0] => Array
(
[id[3]] => BX-78
[Name[3]] => AAA
[Address[3]] => FSDSDS
)
[1] => Array
(
[id[0]] => BX-78
[Name[0]] => XXX
[Address[0]] => YUUSATD
)
)
[1] => Array
(
[0] => Array
(
[id[4]] => BX-81
[Name[4]] => XXX
[Address[4]] => DSDSDSD
)
[1] => Array
(
[id[0]] => BX-78
[Name[0]] => XXX
[Address[0]] => YUUSATD
)
)
)
Demo here: https://3v4l.org/JAtNU
In case someone of you are searching unique values by key.
function unique_multidim_array($array, $key) {
$temp_array = array();
$i = 0;
$key_array = array();
foreach($array as $val) {
if (!in_array($val[$key], $key_array)) {
$key_array[$i] = $val[$key];
$temp_array[$i] = $val;
}
$i++;
}
return $temp_array;
}
This function just takes multidimensional array and key value of field you need.
Then takes value of given array one by one (smaller arrays).
Then traverses given array and looking if taken key-value pair matches with given key.
After that if taken key-value pair matches with given key function just inserts smaller array in temporary array (array with unique values).
Don't forget to increment indexes of arrays ($i).
Then return array you got (with unique values) after function ends work.

Merge array with varying key value pairs

So I have various arrays which do not always have the same key/value pairs in them. What I want to do is to be able to merge the arrays, but to add in empty key/value pairs if they don't already exist in that array, but do in others. It's hard to explain but this might explain it better:
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
I need to somehow turn this into:
$finalArray = array(
array('name' => 'rory', 'car' => 'opel', 'dog' => ''),
array('name' => 'john', 'car' => '', 'dog' => 'albert')
);
I have been looking through PHP's documentation but can't find anything that will do this for me. Can anyone point me in the right direction? I don't even know an appropriate search term for what I want to achieve here, "array merge" isn't specific enough.
<?php
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
$diff1=array_diff(array_flip($arrayOne), array_flip($arrayTwo));
$diff2=array_diff(array_flip($arrayTwo), array_flip($arrayOne));
//array_flip flips the key of array with value
//array_diff would return the values in the first array that are not present in any of the other arrays inside
foreach ($diff2 as $s) {
$arrayOne[$s]="";
}
foreach ($diff1 as $s) {
$arrayTwo[$s]="";
};
//set key that didn't exist in that array as ""
$finalArray[]=$arrayOne;
$finalArray[]=$arrayTwo;
//add the arrays to the final array
print_r($finalArray);
Here's what I would do:
Merge your separate arrays into one (into a temporary var) using array_merge
Get the unique keys of this new array using array_keys
For each separate array, loop through the new keys array and add an empty value for each key that is not in the array. Then push the separate array into a final array.
<?php
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
$new = array_merge($arrayOne,$arrayTwo);
$new = array_keys($new);
$newarray = array();
foreach($new as $value){
$newarray[0][$value] = isset($arrayOne[$value]) ? $arrayOne[$value] : '' ;
$newarray[1][$value] = isset($arrayTwo[$value]) ? $arrayTwo[$value] : '' ;
}
echo "<pre>";print_r($newarray);
You can also use this short answer
$arrayOne = array('name' => 'rory', 'car' => 'opel');
$arrayTwo = array('name' => 'john', 'dog' => 'albert');
$defaults = array('name' => '','car' => '','dog' => '');
$arrayOne += $defaults;
$arrayTwo += $defaults;
$newarray = array($arrayOne,$arrayTwo);
echo "<pre>";print_r($newarray);
Basing on what Justin Powell outlined, I managed to come up with this code before the other two code examples were posted (thank you mamta & user6439245).
I also needed to take the keys containing numbers and sort them appropriately, otherwise my keys would've been indexed like employer_1, education_1, employer_2, education_2.
// get the initial form entries data
$entries = array(
array('name' => 'john', 'car' => 'fiat', 'employer_1' => 'tangerine', 'education_1' => 'hideaways', 'education_2' => 'extras'),
array('name' => 'rory', 'car' => 'opel', 'employer_1' => 'sagittarius', 'employer_2' => 'tangerine', 'employer_3' => 'thehideout', 'education_1' => 'knatchbull')
);
// create an empty array to populate with all field keys
$mergedKeys = array();
// push all field keys into the array
foreach($entries as $entry){
foreach($entry as $key => $value){
array_push($mergedKeys, $key);
}
}
// remove duplicate keys from the array
$uniqueMergedKeys = array_unique($mergedKeys);
// create a new array to populate with the field keys we need to sort - the ones with numbers in
$keysToSort = array();
// push the number-containing keys into the array
$i=0;
foreach($uniqueMergedKeys as $uniqueKey){
if(1 === preg_match('~[0-9]~', $uniqueKey)){
array_push($keysToSort, $uniqueKey);
}
$i++;
}
// remove the number containing keys from the unique keys array
$uniqueMergedKeys = array_diff($uniqueMergedKeys, $keysToSort);
// sort the keys that need sorting
sort($keysToSort);
// put the newly sorted keys back onto the original keys array
foreach($keysToSort as $key){
array_push($uniqueMergedKeys, $key);
}
$final = array();
$i = 0;
foreach($entries as $entry){
foreach($uniqueMergedKeys as $key){
//if($entries[$i][$key]){
if (array_key_exists($key, $entries[$i])) {
$final[$i][$key] = $entries[$i][$key];
} else {
$final[$i][$key] = '';
}
}
$i++;
}
echo '<pre>'; print_r($final); echo '</pre>';

Searching an array of associate arrays for two matching parameters

I have a loop that builds an array of associative arrays that looks like this:
array(
'foo' => '',
'bar' => '',
'thingys' => array()
)
on each iteration of the loop, I want to search through the array for an associate array that's 'foo' and 'bar' properties match those of the current associate array. If it exists I want to append the thingys property of the current associative array to the match. Otherwise append the entire thing.
I know how to do this with for loops, but I'm wondering if there is a simpler way to do this with an array function. I'm on php 5.3.
Example
<?php
$arr = array(
array(
'foo' => 1,
'bar' => 2,
'thing' => 'apple'
),
array(
'foo' => 1,
'bar' => 2,
'thing' => 'orange'
),
array(
'foo' => 2,
'bar' => 2,
'thing' => 'apple'
),
);
$newArr = array();
for ($i=0; $i < count($arr); $i++) {
$matchFound = false;
for ($j=0; $j < count($newArr); $j++) {
if ($arr[$i]['foo'] === $newArr[$j]['foo'] && $arr[$i]['bar'] === $newArr[$j]['bar']) {
array_push($newArr[$j]['thing'], $arr[$i]['things']);
$matchFound = true;
break;
}
}
if (!$matchFound) {
array_push($newArr,
array(
'foo' => $arr[$i]['foo'],
'bar' => $arr[$i]['bar'],
'things' => array($arr[$i]['thing'])
)
);
}
}
/*Output
$newArr = array(
array(
'foo' => 1,
'bar' => 2,
'things' => array('orange', 'apple')
),
array(
'foo' => 2,
'bar' => 2,
'things' => array('apple')
),
)
*/
?>
I don't know if it is possible through a built-in function, but I think no. Something can be implemented through array_map, but anyway you have to perform a double loop.
I propose you a one-loop solution using a temporary array ($keys) as index of already created $newArr items, based on foo and bar; elements of original array are processed through a foreach loop, and if a $keys element with first key as foo value and second key as bar value exists, then the current thing value is added to the returned key index of $newArr, otherwise a new $newArray element is created.
$newArr = $keys = array();
foreach( $arr as $row )
{
if( isset( $keys[$row['foo']][$row['bar']] ) )
{ $newArr[$keys[$row['foo']][$row['bar']]]['thing'][] = $row['thing']; }
else
{
$keys[$row['foo']][$row['bar']] = array_push( $newArr, $row )-1;
$newArr[$keys[$row['foo']][$row['bar']]]['thing'] = array( $row['thing'] );
}
}
unset( $keys );
3v4l.org demo
Edit: array_map variant
This is the same solution above, using array_map instead of foreach loop. Note that also your original code can be converted in this way.
$newArr = $keys = array();
function filterArr( $row )
{
global $newArr, $keys;
if( isset( $keys[$row['foo']][$row['bar']] ) )
{ $newArr[$keys[$row['foo']][$row['bar']]]['thing'][] = $row['thing']; }
else
{
$keys[$row['foo']][$row['bar']] = array_push( $newArr, $row )-1;
$newArr[$keys[$row['foo']][$row['bar']]]['thing'] = array( $row['thing'] );
}
}
array_map( 'filterArr', $arr );
3v4l.org demo

PHP Find a value in a key and get the value of another key in a multi-dimentional array

Might be a newbie question but I've been trying to figure this problem and it's doing my head in.
I have the following array :
[0] => Array
(
[provisionalBookingRoomID] => 1
[totalSpecificRoomCount] => 2
)
[1] => Array
(
[provisionalBookingRoomID] => 2
[totalSpecificRoomCount] => 5
)
I need a php function that searches through the array for the value of 'provisionalBookingRoomID' and returns the value of 'totalSpecificRoomCount'
basically something like the following
getProvisionalTotalRoomsCount($currentRoom, $arrayOfRooms);
// getProvisionalTotalRoomsCount('1', $arrayOfRooms) should return 2;
Any ideas?
Check this:
getProvisionalTotalRoomsCount($currentRoom, $arrayOfRooms){
foreach($arrayOfRooms as $key=>$value){
if($value['provisionalBookingRoomID'] == $currentRoom){
return $value['totalSpecificRoomCount'];
}
}
}
For anyone looking for a generic function :
function findValueInArray($array, $searchValue, $searchKey, $requiredKeyValue) {
foreach($array as $key=>$value){
if($value[$searchKey] == $searchValue){
return $value[$requiredKeyValue];
}
}
}
// Usage : findValueInArray($provisionalBookedRoomsArray, '1', 'provisionalBookingRoomID', 'totalSpecificRoomCount');
If you are likely to work with more than one value, you could build a new array with a 1->1 map for those attributes.
<?php
$items = array(
array(
'name' => 'Foo',
'age' => 23
),
array(
'name' => 'Bar',
'age' => 47
)
);
// Php 7
$name_ages = array_column($items, 'name', 'age');
echo $name_ages['Foo']; // Output 23
// Earlier versions:
$name_ages = array();
foreach($items as $value)
{
$name_ages[$value['name']] = $value['age'];
}
echo $name_ages['Foo']; // Output 23
$value = 0;
$array = array(array("provisionalBookingRoomID"=>1,"totalSpecificRoomCount"=>2),array("provisionalBookingRoomID"=>2,"totalSpecificRoomCount"=>5));
array_map(
function($arr) use (&$value) {
if($arr['provisionalBookingRoomID']==1) {
$value = $arr['totalSpecificRoomCount'];
}
},$array
);
echo $value;

Best way to get keys and its values from an array which are not existent in another array compared only by its keys

hi I wanted to have some keys and values filtered out when compared with another array.
The "content" pair should be displayed at the end...Any help is greatly appreciated THX alot!
<?php
$test = array(
['slideid'] => 597,
['token'] =>'4e23fdd176372984870a9c65db7133b5',
['content'] =>'<p>sdg</p>',
)
$test2 = array(
['slideid'] => "",
['token'] =>""
)
foreach ($test not in $test2){
print $test2
} //not working of course
?>
This works:
$test = array(
'slideid' => 597,
'token' =>'4e23fdd176372984870a9c65db7133b5',
'content' =>'<p>sdg</p>'
);
$test2 = array(
'slideid' => "",
'token' =>""
);
foreach ($test as $key => $value){
if (!array_key_exists($key, $test2)) {
echo $value;
}
}
$arr contains the element that is in test but not test2
$arr = array_diff(array_keys($test), array_keys($test2));
print_r($arr);

Categories