Hey folks, please lend a hand to a PHP beginner. I'm trying to put a load of dynamically created variabled into an array to re-read later, reason is a SOAP message sent is a mess and im trying to create a less complicated array:
$placea = "place a";
$placeb = "place b";
$myarray = array();
echo "<pre>";
print_r($myarray);
echo "</pre>";
what i want to be able to do:
Array
(
[0] => [Place A] => Array
(
[0] => [Accommodation] => Array
(
[RoomId] => 001
[RoomAvail] => true
[Date] => 12.04.2011
)
[1] => [Accommodation] => Array
(
[RoomId] => 002
[RoomAvail] => true
[Date] => 12.04.2011
)
) Array
(
[1] => [Place B] => Array
(
[0] => [Accommodation] => Array
(
[RoomId] => 101
[RoomAvail] => true
[Date] => 12.04.2011
)
[1] => [Accommodation] => Array
(
[RoomId] => 102
[RoomAvail] => true
[Date] => 12.04.2011
)
)
)
how would i write that out in php? sorry if its bleek and/or the array structure is incorrect
So you just need to use the array initializer repetitively.
If you want to initialize an array in PHP with some values, say 1 through 4, you make a call like:
$foo = array(1, 2, 3, 4);
And if you want to make an associative array, where you store some key/value pairs, you make a call like:
$foo = array('key' => 'value', 'other key' => 'other value');
But you can of course nest calls, and mix and match layers of associative and non associative arrays to achieve something like your example, e.g.:
$foo = array(
'Place A' => array(
// note use of first array on the next line is
// to generate structure like [0] => 'Accomodation' => ...
array('Accomodation' => array(
'RoomId' => '001',
'RoomAvail' => true,
'Date' => '12.04.2011')
)),
array('Accomodation' => array(
'RoomId' => '002',
'RoomAvail' => true,
'Date' => '12.04.2011')
))
),
'Place B' => array(
array('Accomodation' => array(
'RoomId' => '101',
'RoomAvail' => true,
'Date' => '12.04.2011')
)),
array('Accomodation' => array(
'RoomId' => '102',
'RoomAvail' => true,
'Date' => '12.04.2011')
))
)
);
This will very nearly produce what you're looking for, to make it replicate exactly what you have you would wrap each 'Place A' with an array and each "place" would get its own assignment to some variable $foo (I assumed this wasn't actually what you wanted and wrote something maybe slightly more intuitive).
If you want to have a 'less complicated' array, you have a two arrays, one fore place a and one for place b and then merge them using array_merger() http://www.php.net/manual/en/function.array-merge.php.
Study up on the array functions control structures in the manual. Many different ways of achieving bloated arrays uglying up your code.
This would dynamically create an array.
foreach($soapResponse as $key1 => $value1){
foreach($value as $key2 => $value2){
// $key1 = Place A or B
// value1 = array of values
$arrayResponse[$key1][$key2] = $value2;
}
}
Related
I have a associative array(shown below). I want to send $demographics['customer'] to a function and access both the key and value of the array.
function sendValues($data) {
print_r($data);
}
$demographics = array(
'customer' => array('name' => 'John', 'age' => 28),
'offers' => array('value' => '10.00', 'expiration' => '2021-10-01')
);
//print_r($demographics);
sendValues($demographics['customer']);
Actual:
Array
(
[name] => John
[age] => 28
)
Expected:
Array
(
[customer] => array(
[name] => John
[age] => 28
)
)
If you just need to send a specific part of the array to the function, you can also use array_slice(). Like with the first element like this:
sendValues(array_slice($demographics, 0, 1));
Also refer to: https://www.php.net/manual/en/function.array-slice.php
create a new array with only the customers key then,
sendValues(array(
"customer"=>$demographics['customer']
));
please excuse if this question is already answered elsewhere, but I just don't know what to search for, since I usually don't work with php.
I've got the following array:
(
[0] => Array
(
[login] => name23
[id] => 12356
)
[1] => Array
(
[login] => name12
[id] => 12345
)
[2] => Array
(
[login] => name34
[id] => 12367
)
)
And I'd like to only print the login-names, so in this example name23, name12, name34 (But I never know how many there are).
I've tried several approaches with foreach, which didn't work.
What is working, but only for one username is this:
echo $contributors[0]['login'];
How can I display all login-names?
Any help would be much appreciated.
Thanks in advance!
array_map is a universal function for tasks like this, in your case, this code would work:
$array = [['login' => "name23", 'id' => 12356], ['login' => "name12", 'id' => 12345], ['login' => "name34", 'id' => 12367]];
print_r(array_map(function($data) { return $data['login']; }, $array));
Manual: https://www.php.net/array-map
But for your specific task, array_column is simpler, as recommended by Aghilan B.
There is also array_walk function that can be used like this:
$array = [['login' => "name23", 'id' => 12356], ['login' => "name12", 'id' => 12345], ['login' => "name34", 'id' => 12367]];
array_walk($array, function($data) { print $data['login'] . "\n"; });
That can be useful if you want to do more with the logins than just printing it, it would not need to iterate twice.
You can use array_column() Function
$array = [['login' => "name23", 'id' => 12356], ['login' => "name12", 'id' => 12345], ['login' => "name34", 'id' => 12367]];
$login_array = array_column($array, 'login');
print_r($login_array);
Output
Array
(
[0] => "name23"
[1] => "name12"
[2] => "name34"
)
Use implode(', ', $login_array); to print as a string with commas
This question already has answers here:
Filter/Remove rows where column value is found more than once in a multidimensional array
(4 answers)
Closed 9 months ago.
I'm trying to remove all keys with repeated numbers, I've tried some solutions posted here like the one I'm using in my script but none of it worked for my purpose.
This is my array:
There are at least 4 card IDs repeated.
Array
(
[0] => Array
(
[id_card] => 11883834
[type] => 1
[registed] => 1547610891
)
[1] => Array
(
[id_card] => 20311077
[type] => 1
[registed] => 1547610891
)
[2] => Array
(
[id_card] => 16187903
[type] => 3
[registed] => 1547610891
)
[3] => Array
(
[id_card] => 16354099
[type] => 1
[registed] => 1547610891
)
[4] => Array
(
[id_card] => 21133393
[type] => 4
[registed] => 1547610891
)
[5] => Array
(
[id_card] => 15452852
[type] => 2
[registed] => 1547610891
)
[6] => Array
(
[id_card] => 19775869
[type] => 2
[registed] => 1547610891
)
[7] => Array
(
[id_card] => 20311077
[type] => 1
[registed] => 1547610891
)
[8] => Array
(
[id_card] => 21133393
[type] => 4
[registed] => 1547610891
)
[9] => Array
(
[id_card] => 11883834
[type] => 1
[registed] => 1547610891
)
)
1
At the moment I have something like this:
<?php
$array_data = array_map('unserialize', array_unique(array_map('serialize', $myArray)));
echo '<pre>';
print_r($array_data);
echo '</pre>';
?>
With only 10 keys is working perfectly, but when it goes through this with, for example, 50, 100 keys, no longer works.
Any help appreciated.
So the issue here is that the array_unique solutions expect the entire value to be equivalent - they don't just compare based on your ID field.
Instead, you probably want to loop through the array and keep track of which IDs you've seen, and only take those elements for which you haven't seen the ID before.
function filter_duplicate_id_cards($data) {
$seen = array(); // To keep track of the IDs we've seen
$filtered = array(); // Will hold the result
foreach($data as $item) {
if(array_key_exists($item['id_card'], $seen)) {
// We already encountered this id card before.
continue;
}
// Never-before seen id card, append it to the result and set the key in $seen
$filtered[] = $item;
$seen[$item['id_card']] = TRUE;
}
return $filtered;
}
Note that this uses the map form of a PHP array, rather than just appending seen IDs to the list form and using something like in_array to check if we've seen the key. That's important for performance reasons, especially if we're going to be working on large datasets - in_array is O(n) with the # of items in the array whereas array_key_exists is O(1).
A more generic version of this function would look like this:
function filter_duplicate_field($data, $field) {
$seen = array(); // To keep track of the keys we've seen
$filtered = array(); // Will hold the result
foreach($data as $item) {
if(array_key_exists($item[$field], $seen)) {
// We already encountered this key before.
continue;
}
// Never-before seen key, append it to the result and set the key in $seen
$filtered[] = $item;
$seen[$item[$field]] = TRUE;
}
return $filtered;
}
You could then call it like $result = filter_duplicate_field($data, 'id_card');.
This doesn't preserve the original input order, but because the data is indexed so I'll assume that that doesn't matter.
With just 3 calls in a one-liner, you assign temporary associative keys from back to front to eliminate latter duplicates (because php does not permit duplicate keys), then optionally remove the temporary keys with array_values(). No iterated function calls. No lookup arrays.
Code: (Demo)
$array = [
['id_card' => 11883834, 'type' => 1, 'registed' => 1547610891],
['id_card' => 20311077, 'type' => 1, 'registed' => 1547610891],
['id_card' => 16187903, 'type' => 3, 'registed' => 1547610891],
['id_card' => 16354099, 'type' => 1, 'registed' => 1547610891],
['id_card' => 21133393, 'type' => 4, 'registed' => 1547610891],
['id_card' => 15452852, 'type' => 2, 'registed' => 1547610891],
['id_card' => 19775869, 'type' => 2, 'registed' => 1547610891],
['id_card' => 20311077, 'type' => 1, 'registed' => 1547610891],
['id_card' => 21133393, 'type' => 4, 'registed' => 1547610891],
['id_card' => 11883834, 'type' => 1, 'registed' => 1547610891]
];
var_export(array_values(array_column(array_reverse($array), null, 'id_card')));
If you change you mind about wanting to keep the first occurrence, you can remove array_reverse(). If the first level keys are irrelevant in the output, you can remove array_values(). These changes would allow the solution to be a one function call task.
p.s. "registered"
maybe I am totally blind but i have an array:
Array ( [p541] => 1 [p747] => 1 [p792] => 1 [p968] => 1 [p2157] => 1 [clickeditem] => 0WCr9ParDzLD9wpctknt0XErhOZcX33wXfgGDNpSoIo= [actualtime] => 11832 [timekey] => 1406227645 [actualuser_id] => V58yD4MQ2ZwTumjivhhQL/BSFXsu0Dvoj0bxp7Tu8PM= [timeout] => 0 [report_misuse] => 0 [A1] => 5RC52CZHPV8f0Zw+FYGZel5Ay2YcLVjrY8MBplz1zJA= [B1] => 0WCr9ParDzLD9wpctknt0XErhOZcX33wXfgGDNpSoIo= [B2] => KnCK/vIcQ5PAwJxjUMh0w+NTM+TqdVG9+Tiyi0U9QWM= [B3] => DhT8qBQFQC+dE/Rku7wdMJ4bw6dtFp8hzfmxPMCrItQ= [B4] => ZE30ASB6IUQglpXNiOUxdmiYpJnEbuKKXIaUZO9w4mU= [B5] => IXyGTO6V/8uZOK5y81DnI58xumZ0CIkFsTQwUWJ2CyE= [pageloadtime] => 0.179646 [option] => com_findme [view] => pair )
but I want to get the value for "p541"
$name= "p541";
$value = $array [$name];
does not work ???
If your array variable is named $array, try this:
$value = $array['p541'];
What you're doing is creating a new array named $value containing the variable $name, which is not what we want.
Your array items need to be comma separated and not within [ ] if you're declaring associative arrays like that. You also need to save your array to a variable so you can access it.
$value = array('p541' => 1, 'p747' => 2, 'p792' => 3);
then this...
$value['p541']
will equal 1
There is the following array in my application:
array (
[item_name_1] => GTA V
[item_quantity_1] => 4
[item_price_1] => 5990
[item_name_2] => Watch_Dogs
[item_quantity_2] => 1
[item_price_2] => 5990
)
I want to divide/split this array into two pieces like that:
array (
[item_name_1] => GTA V
[item_quantity_1] => 4
[item_price_1] => 5990
)
array (
[item_name_2] => Watch_Dogs
[item_quantity_2] => 1
[item_price_2] => 5990
)
If you didn't realized, I want to separate items suffixed by 1 and 2 – and successively – unto different matrices and I really don't see the best way to perform this. Maybe regex?
I already tried to play with explode() and implode(), but no success – I have no creativity enough to explore their best.
<?php
$src = array (
'item_name_1' => 'GTA V',
'item_quantity_1' => 4,
'item_price_1' => 5990,
'item_name_2' => 'Watch_Dogs',
'item_quantity_2' => 1,
'item_price_2' => 5990,
);
$dest = array();
foreach($src as $k => $v) {
$sfx = preg_replace('/.*?_([0-9]+)$/', '$1',$k);
$dest[$sfx][$k] = $v;
}
print_r($dest);