I have following array and getting this result:
Array
(
[0] => stdClass Object
(
[UnitIdx] => 10
[Title] => 순차
[Description] =>
[NumSteps] => 9
[ThumbnailPathName] => Level_1_Unit_thumbnail_Small.png
[Step_1] => 4
[Step_2] => 5
[Step_3] => 6
[Step_4] => 7
[Step_5] => 8
[Step_6] => 9
[Step_7] => 10
[Step_8] => 11
[Step_9] => 12
[Step_10] => 0
[Step_11] => 0
[Step_12] => 0
[Step_13] => 0
[Step_14] => 0
[Step_15] => 0
[Step_16] => 0
[Step_17] => 0
[Step_18] => 0
[Step_19] => 0
[Step_20] => 0
)
)
Now I want to find key form value. For example value is 11 so key is Step_8.
Any idea how to return key name from value?
Thanks.
You can search your key by value using array_search() and converting your Object into PHP array by typecasting, below is an example:
<?php
$object = array();
$object[0] = new StdClass;
$object[0]->foo = 1;
$object[0]->bar = 2;
echo "<pre>";
print_r($object);
echo "</pre>";
$key = array_search ('2', (array) $object[0]);
echo "<pre>";
print_r($key);
?>
Output:
Array
(
[0] => stdClass Object
(
[foo] => 1
[bar] => 2
)
)
bar
Take a look at this:
<?php
//this part of code is for prepare sample data which is similar to your data
$class = new stdClass;
$class->prop1 = 'prop1';
$class->prop2 = 'prop2';
$array = array($class);
//THIS IS METHOD FOR SEARCH KEY BY VALUE
print_r(array_search('prop1',json_decode(json_encode($array[0]), true))); //you are looking for key for value 'prop1'
Check working fiddle: CLICK!
Explanation:
1) json_decode(json_encode($array[0]), true) - because you have in your array stdClass object, you can't use array_search function. So this line converts $array[0] element, which is stdClass object to an array. Now we can use array_search function to search key by specific value.
2) print_r(array_search('prop1',json_decode(json_encode($array[0]), true))); - we are using array_search function to get key of array element which value is equal to prop1. Documentation of this function says:
array_search — Searches the array for a given value and returns the
corresponding key if successful
So we getting key corresponding to prop1 value, which is prop1. print_r function shows us result. Instead of that you can assign result of operation to a variable and use it in other parts of code, for example:
$variable = array_search('prop1',json_decode(json_encode($array[0]), true));
Related
$original array [['type_of_activity'=>'م.ص','total'=>'0' ],['type_of_activity'=>'م.و','total'=>'0'],['type_of_activity'=>'م.ن','total'=>'0'],['type_of_activity'=>'م.خ','total'=>'0'],['type_of_activity'=>'م.ت','total'=>'0'],['type_of_activity'=>'و.ش','total'=>'0'],['type_of_activity'=>'ق.ع','total'=>'0'],
['type_of_activity'=>'م.و','total'=>'0'],['type_of_activity'=>'م.غ','total'=>'0'],['type_of_activity'=>'س.ن','total'=>'0'],['type_of_activity'=>'ح.ف','total'=>'0']]
that there areport based on this value
the return array from DB my be ['type_of_activity'=>'م.و','total'=>'5'],['type_of_activity'=>'م.غ','total'=>'10'],['type_of_activity'=>'س.ن','total'=>'15']
is there a way to map this array to the original array where the match keys
without losing any key or value
the result will be just 11 arrays within the original
[['type_of_activity'=>'م.ص','total'=>'0' ],
[['type_of_activity'=>'م.ع','total'=>'0' ],
['type_of_activity'=>'م.و','total'=>'5'],['type_of_activity'=>'م.ن','total'=>'0'],['type_of_activity'=>'م.خ','total'=>'0'],['type_of_activity'=>'م.ت','total'=>'0'],['type_of_activity'=>'و.ش','total'=>'0'],['type_of_activity'=>'ق.ع','total'=>'0'], ['type_of_activity'=>'م.غ','total'=>'10'],['type_of_activity'=>'س.ن','total'=>'15'],['type_of_activity'=>'ح.ف','total'=>'0']],
You can use array_merge,
$c = array_merge($a,$b);
print_r($c);
Demo
O/p
Array
(
[mw] => 0
[mg] => 5
[ma] => 0
[sn] => 0
[fa] => 0
[mn] => 10
)
When I do a print_r on my $_POST, I have an array that may look like this:
Array
(
[action] => remove
[data] => Array
(
[row_1] => Array
(
[DT_RowId] => row_1
[name] => Unit 1
[item_price] => 150.00
[active] => Y
[taxable] => Y
[company_id] => 1
)
)
)
The row_1 value can be anything formatted like row_?
I want that number as a string, whatever the number is. That key and the DT_RowID value will always be the same if that helps.
Right now I am doing this, but it seems like a bad way of doing it:
//the POST is a multidimensinal array... the key inside the 'data' array has the id in it, like this: row_2. I'm getting the key value here and then removing the letters to get only the id nummber.
foreach ($_POST['data'] AS $key => $value) {
$id_from_row_value = $key;
}
//get only number from key = still returning an array
preg_match_all('!\d+!', $id_from_row_value, $just_id);
//found I had to use [0][0] since it's still a multidimensional array to get the id value
$id = $just_id[0][0];
It works, but I'm guessing there's a faster way of getting that number from the $_POST array.
<?php
$array = [
'data' => [
'row_1' => [],
'row_2' => [],
]
];
$nums = [];
foreach ($array['data'] as $key => $val) {
$nums[] = preg_replace('#[^\d]#', '', $key);
}
var_export($nums);
Outputs:
array (
0 => '1',
1 => '2',
)
Please remember that regular expressions, used in preg_match are not the fastest solution. What I would do is split the string by _ and take the second part. Like that:
$rowId = explode("_", "row_2")[1];
And put that into your loop to process all elements.
I have this simple array in PHP that I need to filter based on an array of tags matching those in the array.
Array
(
[0] => stdClass Object
(
[name] => Introduction
[id] => 798162f0-d779-46b6-96cb-ede246bf4f3f
[tags] => Array
(
[0] => client corp
[1] => version 2
)
)
[1] => stdClass Object
(
[name] => Chapter one
[id] => 761e1909-34b3-4733-aab6-ebef26d3fcb9
[tags] => Array
(
[0] => pro feature
)
)
)
When supplied with 'client corp', the output should be the above array with only the first item.
So far I have this:
$selectedTree = array_filter($tree,"checkForTags");
function checkForTags($var){
$arr = $var->tags;
$test = in_array("client corp", $arr, true);
return ($test);
}
However, the result is that it's not filtering. When I echo $test, I get 1 all the time. What am I doing wrong?
Something like this should do the trick:
$selectedTree = array_filter(array_map("checkForTags", $tree ,array_fill(0, count($tree), 'client corp')));
function checkForTags($var, $exclude){
$arr = $var->tags;
$test = in_array($exclude, $arr, true);
return ($test ? $var : false);
}
array_map() makes sure you can pass arguments to the array. It returns each value altered. So in the returning array, some values are present, others are set to false. array_filter() with no callback filters all falsey values from that array and you are left with the desired result
The in_array() function returns TRUE if needle is found in the array and FALSE otherwise. So by getting 1 as a result that means that "client corp" is found.
Check PHP in_array() manual
You can user array_search() to return the array key instead of using in_array().
I have and array that is being produced from a webservice.
Array (
[TPA_Extensions] => Array (
[TPARoomDetail] => Array (
[GuestCounts] => Array (
[GuestCount] => Array (
[!AgeQualifyingCode] => 10
[!Count] => 1
)
)
[!Occupancy] => Single
[!OccupancyCode] => SGL
)
)
[!IsRoom] => true
[!Quantity] => 1
[!RoomType] => Palace Gold Club Room
[!RoomTypeCode] => PGC
)
My foreach loop is as below
foreach ($roomType["TPA_Extensions"]["TPARoomDetail"]["GuestCounts"]["GuestCount"] as $guestcount) {
echo "guest count1->";print_r($guestcount);
echo "guest count2->"; print_r($roomType["TPA_Extensions"]["TPARoomDetail"]["GuestCounts"]["GuestCount"]);
}
The output i get is
guest
count1->10 guest count2->Array ( [!AgeQualifyingCode] => 10 [!Count] => 1 )
guest count1 should have been an array
Array ( [!AgeQualifyingCode] => 10 [!Count] => 1 ) but it comes as an int 10 ..
why is that so ..?
Your output is correct, $guestcount holds the number '10',
where $roomType["TPA_Extensions"]["TPARoomDetail"]["GuestCounts"]["GuestCount"]
hold an array.
this is your loop:
foreach ($roomType["TPA_Extensions"]["TPARoomDetail"]["GuestCounts"]["GuestCount"] as $guestcount) {
echo "guest count1->";print_r($guestcount);
echo "guest count2->"; print_r($roomType["TPA_Extensions"]["TPARoomDetail"]["GuestCounts"]["GuestCount"]);
}
ths loop will run 2 times, because that's the number of childs in GuestCount array.
it will be '10', then '1', exactly reflecting the structure of your array:
[!AgeQualifyingCode] => 10
[!Count] => 1
Theres nothing wrong in the code as 1st index holds integer value and 2nd index holds array. However your method of accessing array value are very complicated and doesn't looks good. You an access the array values and keys in more effective manner as follows.
1)Create a method that takes path of the array you want to access
For example According to your code if I want to access AgeQualifyingCode key than I have to write $roomType["TPA_Extensions"]["TPARoomDetail"]["GuestCounts"]["GuestCount"]["AgeQualifyingCode"].
This doesn't looks good, wouldn't it be great if you just have to pass the path of key you want to access the value to.
For example: /TPA_Extensions/TPARoomDetail/GuestCounts/GuestCount/AgeQualifyingCode
You just have to define a function that takes the path of the key, and will return value for that key
<?php
function path($path=null){
if($path){
$array = $theNameOfOriginalArray
$path = explode('/',$path);
foreach($path as $sub){
if(isset($array[$sub])){
$array = $array[$sub];
}
}
return $array;
}
}
$value = path('TPA_Extensions/TPARoomDetail/GuestCounts/GuestCount/AgeQualifyingCode');
//will return 10
?>
I have an array in PHP that looks like
Array ( [123654] => Array ( [0] => 123456789123456789 [1] => 1 [2] => 06/24/2011 [3] => 06/24/2012 [4] => 12355.44 [5] => 55321.55 ) )
I know in javascript I could access the data I need by doing array[0][0], how would I go about doing this in PHP. It is the 123456789123456789 value that I'm looking at getting.
Try this
array_slice($array, 0, 1);
http://php.net/array_slice
If you don't know the exact keys, you could do something like this:
$a = array_values($my_array);
$b = array_values($a[0]);
echo $b[0];
array_values replaces the keys by simple numbers from 0 to n-1 (where n is the count of values), by that you can access your desired value with the indexes [0][0]. See more here
http://codepad.org/YXu6884R
Here you go. See above for proof. The methodology from #azat is not explicit enough and is prone to risk if the elements of the array or sub array are re-arranged or if the key value for the super array changes.
$my_array = array( 123654 => array( 0 => '123456789123456789', 1 => '1', 2 => '06/24/2011', 3 => '06/24/2012', 4 => '12355.44', 5 => '55321.55' ) );
echo $my_array['123654'][0];
Try
$first = array_shift(array_values($array));
http://php.net/manual/en/function.array-shift.php