Validate matching array keys - php

Given the following arrays how can I elegantly validate that option, price and cost arrays have matching key values?
Array
(
[option] => Array
(
[1] => C
[2] => M
[3] => G
)
[price] => Array
(
[1] => 100
[2] => 200
[3] => 300
)
[cost] => Array
(
[1] => 0
[2] => 0
[3] => 0
)
)
I thought of running a foreach(array as key => values) on each array and sending those values to another array, and then using if(!in_array), but theres got to be a better way to do it.

It sounds like you want the same keys as there is no correlation with the values in the array. If so, you can run a diff on the keys of each sub-array:
if(call_user_func_array('array_diff_key', $array)) {
// not the same keys
} else {
// same keys
}
call_user_func_array() takes the array as an array of arguments and passes each to array_diff_key()
If the result is not empty then there are differences
If the result is empty then there are no differences

I recommend using an array in this way:
Array
(
[option] => Array
(
[C] => Array
(
[price] => 100
[cost] => 0
)
[M] => Array
(
[price] => 200
[cost] => 0
)
[G] => Array
(
[price] => 300
[cost] => 0
)
)
)
PHP Code:
$product = array("option" => array("C" => array("price" => 100, "cost" => 0), "M" => array("price" => 200, "cost" => 0), "G" => array("price" => 300, "cost" => 0)));

Related

merge two equal structural multi-arrays with different data

i can't believe that i can't find a solution to this seemingly simple problem, and i tried everything.
i have two multi arrays:
the first one:
Array
(
[3] => Array
(
[1] => Array
(
[approved] => 1
[id_note] => 1
[surname] => Rawson
)
[2] => Array
(
[approved] =>
[id_note] => 18
[surname] => Vallejo
)
)
[4] => Array
(
[1] => Array
(
[school_id] => 1
)
[2] => Array
(
[available] => 1
)
)
)
the second one has the exact same structure, but with new data:
Array
(
[3] => Array
(
[1] => Array
(
[final_approved] => 1
[final_id_note] => 1
)
[2] => Array
(
[final_approved] =>
[final_id_note] => 19
)
)
)
what i need mergin both multi-arrays is this result:
Array
(
[3] => Array
(
[1] => Array
(
[approved] => 1
[id_note] => 1
[surname] => Rawson
[final_approved] => 1
[final_id_note] => 1
)
[2] => Array
(
[approved] =>
[id_note] => 18
[surname] => Vallejo
[final_approved] =>
[final_id_note] => 19
)
)
[4] => Array
(
[1] => Array
(
[school_id] => 1
)
[2] => Array
(
[available] => 1
)
)
)
but i can't get this result with any common php function:
array_merge:
Array
(
[0] => Array
(
[1] => Array
(
[approved] => 1
[id_note] => 1
[surname] => Rawson
)
[2] => Array
(
[approved] =>
[id_note] => 18
[surname] => Vallejo
)
)
[1] => Array
(
[1] => Array
(
[school_id] => 1
)
[2] => Array
(
[available] => 1
)
)
[2] => Array
(
[1] => Array
(
[final_approved] => 1
[final_id_note] => 1
)
[2] => Array
(
[final_approved] =>
[final_id_note] => 19
)
)
)
it replaces with new indexes.
array_push:
Array
(
[3] => Array
(
[1] => Array
(
[approved] => 1
[id_note] => 1
[surname] => Rawson
)
[2] => Array
(
[approved] =>
[id_note] => 18
[surname] => Vallejo
)
)
[4] => Array
(
[1] => Array
(
[school_id] => 1
)
[2] => Array
(
[available] => 1
)
)
[5] => Array
(
[3] => Array
(
[1] => Array
(
[final_approved] => 1
[final_id_note] => 1
)
[2] => Array
(
[final_approved] =>
[final_id_note] => 19
)
)
)
)
it literally pushes in with the second array with new indexes, which is correct of course lol
i guess that the answer is pretty simple, but i already googled and try everything that my newbie ability can.
can anyone give me some advice?
thanks!
There are recursive array functions in PHP. array_merge_recursive, despite the promising name, will not work here, as it will reindex the numeric keys and add overlapping the data to the end.
However, there is array_replace_recursive that does exactly what you want when you have a multidimensional array with significant keys. Here's your data (in a usable format!):
// The base data:
$a_one = [
3 => [
1 => [
'approved' => 1,
'id_note' => 1,
'surname' => 'Rawson',
],
2 => [
'approved' => 0,
'id_note' => 18,
'surname' => 'Vallejo',
],
],
4 => [
1 => [
'school_id' => 1,
],
2 => [
'available' => 1,
],
],
];
// Data to be added by matching keys:
$a_two = [
3 => [
1 => [
'final_approved' => 1,
'final_id_note' => 1,
],
2 => [
'final_approved' => 0,
'final_id_note' => 19,
],
],
];
Then let's mash them together:
$merged = array_replace_recursive($a_one, $a_two);
This results in the following "merged" array:
[
3 => [
1 => [
'approved' => 1,
'id_note' => 1,
'surname' => 'Rawson',
'final_approved' => 1,
'final_id_note' => 1,
],
2 => [
'approved' => 0,
'id_note' => 18,
'surname' => 'Vallejo',
'final_approved' => 0,
'final_id_note' => 19,
],
],
4 => [
1 => [
'school_id' => 1,
],
2 => [
'available' => 1,
],
],
]
In summary, the way this function behaves (from the manual, numbering added):
If a key from the first array exists in the second array, its value will be replaced by the value from the second array.
If the key exists in the second array, and not the first, it will be created in the first array.
If a key only exists in the first array, it will be left as is.
Or in a more compact statement:
key: scalar EXISTS in A, B => REPLACE from B to A
key: scalar EXISTS in B => CREATE in A
key: scalar EXISTS in A => LEAVE in A
Again, the manual says:
When the value in the first array is scalar, it will be replaced by the value in the second array, may it be scalar or array. When the value in the first array and the second array are both arrays, array_replace_recursive() will replace their respective value recursively.
What's important to note here is that array members with matching keys, that are arrays, will not be "replaced" in full. The "replacement" only applies to the final scalar values or "leaves" of the array (per the logic above). The arrays will be "merged", ie. non-matching keys with scalar values will be combined within each "final array" (or "leafy array" for lack of a better term).
N.B. If you're using this function to "merge" more complex arrays, you'll want to double-check that the outcome matches your expectations. I can't remember off the top of my head all the "quirks" that exist in using this function, but I assure you they are there... don't assume that it will create a seamless union of any and all datasets you may throw at it.

PHP Get values from nested array

I am new to PHP and Arrays, I am trying to get the values from an array. But no matter how I'm trying to do it, I can't get the value. What am I doing wrong?
The Array:
Array ( [playerinfo] => Array ( [rank] => Godfather [cash] => € 8,520,530 [weapon] => M-16 (29000) [health] => Array ( [width] => 100 [color] => green ) [wealth] => Too rich to be true [protection] => Bulletproof Humvee [plf] => Huge [plane] => Concorde [crew] => None [pbf] => Large [ship] => None ) [character] => Array ( [crime] => Array ( [0] => 120 [1] => 69 ) [gta] => Array ( [0] => 400 [1] => 70 ) [drugs] => Array ( [0] => 120 [1] => 2528 ) [airport] => Array ( [0] => 2700 [1] => 2529 ) [oc] => Array ( [0] => 86400 [1] => 1442364 ) [tr] => Array ( [0] => 10800 [1] => 1640016011 ) [plf] => Array ( [0] => 7200 [1] => 6712 ) [kill] => Array ( [0] => 3600 [1] => 1640019611 ) ) )
The way I tried to get the info:
$AccData = json_decode($MobinfoString, true);
echo $AccData['playerinfo']['rank'].'<br/>';
echo $AccData['playerinfo']['cash'].'<br/>';
foreach ($AccData as $playerinfo) {
echo $playerinfo['playerinfo']['rank'].'<br/>';
echo $playerinfo['character']['gta'].'<br/>';
}
EDIT:
The json string
{"playerinfo":{"rank":"Boss","cash":"€ 5,923,712","weapon":"M-16 (4500)","health":{"width":"100","color":"green"},"wealth":"Too rich to be true","protection":"Bulletproof Humvee","plf":"Huge","plane":"Concorde","crew":"None","pbf":"Large","ship":"None"},"character":{"crime":[120,122],"gta":[400,369],"drugs":[120,2582],"airport":[2700,2582],"oc":[86400,1640020450],"tr":[10800,1640016850],"plf":[7200,3935],"kill":[3600,1640020450]}}
Anyone knows how to do this ? For example I need the Concorde from plane in a variable and the time values from gta in a variable. And some more from this string.
So your first Part is okay and you rank you can just display like the first part as well
$AccData = json_decode($MobinfoString, true);
echo $AccData['playerinfo']['rank'].'<br/>';
echo $AccData['playerinfo']['cash'].'<br/>';
echo $AccData['playerinfo']['rank'].'<br/>';
echo $AccData['playerinfo']['plane'].'<br/>';
echo $AccData['character']['gta'][0].'<br/>';
but the character is on the same level as playerinfo so you need to access it from AccData. also gta is an array like health, so you have to specify which value you want to show, the first so 0 or second which is 1

How to chage array key value without change array formate in php

Can you please explain how to change one array value to second value.
Please find below example.
First array
Array
(
[20239802] => one test
[20239801] => two testttttt
)
Second array
Array (
[content] => Array (
[0] => Array (
[content_pack_id] => 10002
[content_pack_name] => 100 Days Of Love-FLA
[image_path] => Array ( [0] => pack_image_10002_width. )
[content_image_path] => Array ( [imgjpeg80] => http://content.jpg )
[content_id] => 20239802
[track] => Lede Inthati Santhosham
[duration] => 0
)
[1] => Array (
[content_pack_id] => 10003
[content_pack_name] => 1001 fdfdf
[image_path] => Array ( [0] => pack_image_10002_width. )
[content_image_path] => Array ( [imgjpeg80] => http://content.jpg )
[content_id] => 20239801
[track] => Lede Inthati Santhosham
[duration] => 0
)
)
[autoshuffle_pack] => no
)
We need to replace [track] value in second array if match first array [20239802] with second array [content_id]
Need out put:-
Array
(
[content] => Array
(
[0] => Array
(
[content_pack_id] => 10002
[content_pack_name] => 100 Days Of Love-FLA
[image_path] => Array
(
[0] => pack_image_10002_width.
)
[content_image_path] => Array
(
[imgjpeg80] => http://content.jpg
)
[content_id] => 20239802
[track] => one test
[duration] => 0
)
[1] => Array
(
[content_pack_id] => 10003
[content_pack_name] => 1001 fdfdf
[image_path] => Array
(
[0] => pack_image_10002_width.
)
[content_image_path] => Array
(
[imgjpeg80] => http://content.jpg
)
[content_id] => 20239801
[track] => two testttttt
[duration] => 0
)
)
[autoshuffle_pack] => no
)
Check [track] value change in my need out put
as per depend first array.
Array
(
[20239802] => one test
[20239801] => two testttttt
)
with second array
[content_id] => 20239801
[track] => two testttttt
Is this you want to do :
foreach($second_array as $key => $second_row) {
$content_id = $second_row['content_id'];
if(isset($first_array[$content_id]) && $first_array[$content_id] != '') {
$second_array['track'] = $first_array[$content_id];
}
}
You can do you own function.
Foreach records in your first array:
Loop though the second and search for key == content_id
If it matched, set the value of array2[$index][track] to array1[key]
If not just continue
You can also use array_search() function to find the match faster, for I'll let you take a look at the PHP documentation

Add key and variable to multidimensional Array based on conditions

I wonder if it's possible to add a key and value to an array, based on certain conditions.
This piece of script makes an api-call to retrieve sportresults from multiple teams based on a teamID number.
$length = $numberofTeams
for ($i = 0; $i < $length; $i++) {
$teamID = $objTeamID[$i]['Teamid'];
$teamResults = 'http://api.com/teamresults/' . $Teamid;
$dataResults = file_get_contents($teamResults);
$objResults[] = json_decode($dataResults, true);
}
The result is an array with this structure:
Array (
[0] => Array (
[errorcode] => 9995
[message] => No results
)
[1] => Array (
[errorcode] => 1000
[message] => Ok, Schedule follows
[List] => Array (
[0] => Array (
[MatchID] => 7683403
[Number] => 630
[Result] => 2 - 1
[Datum] => 2013-08-27
[Tijd] => 2000
[CompType] => B )
[1] => Array (
[MatchID] => 7683403
[Number] => 630
[Result] => 4 - 0 [Datum] => 2013-08-27
[Tijd] => 2000
[CompType] => B )
)
)
[2] => Array (
[errorcode] => 9995
[message] => No results )
)
Before saving it in an MySql database, for later use I need to add the teamID-variable to every result so it would become:
Array (
[0] => Array (
[errorcode] => 9995
[message] => No results
)
[1] => Array (
[errorcode] => 1000
[message] => Ok, Schedule follows
[List] => Array (
[0] => Array (
[teamID] => 'value from $teamID'
[MatchID] => 7683403
[Number] => 630
[Result] => 2 - 1
[Datum] => 2013-08-27
[Tijd] => 2000
[CompType] => B )
[1] => Array (
[teamID] => 'value from $teamID' [MatchID] => 7683403
[Number] => 630
[Result] => 4 - 0
[Datum] => 2013-08-27
[Tijd] => 2000
[CompType] => B )
)
)
[2] => Array (
[errorcode] => 9995
[message] => No results )
)
The length of the array varies and also the number of results vary. I have no influence on the result of the api-call itself, because it's been set up by big sport association.
I'm absolutely no programmer, so I'm out of my depth her, but this is a voluntary job for an amateur sportsclub so hiring a programmer is no option.
Rgds, Bonzyx
if(isset($objResults[1]['List'])){
foreach($objResults[1]['List'] as &$listItem){
$listItem['teamID'] = $teamID;
}
unset($listItem); //good practice to unset this reference to last array element
}
You could do the same with php's array_walk() function, but since you said you're not a programmer I think the foreach method is more clear to you.

How to loop through subarray to see if value is return in string

Here is an example of an array that is output:
Array ( [CART] => Array ( [ITEMS] => Array ( [0] => Array ( [product_id] => 269194 [variation_id] => 0 [options] => Array ( ) [quantity] => 1 [product_name] => 15 Top Hits for Easy Piano [product_code] => HL102668 [product_price] => 14.9900 [original_price] => 14.9900 [default_currency] => 1 [customer_group] => [product_fields] => Array ( ) ) [1] => Array ( [product_id] => 266421 [variation_id] => 0 [options] => Array ( ) [quantity] => 1 [product_name] => Whistle [product_code] => HD245839 [product_price] => 3.9900 [original_price] => 3.9900 [default_currency] => 1 [customer_group] => [product_fields] => Array ( ) ) ) [LAST_UPDATED] => 1349829499 [NUM_ITEMS] => 2 ) [JustAddedProduct] => [CHECKOUT] => Array ( ) )
There is an array for each unique product (in this example there are 2 unique products.) Sometimes there will be just one, sometimes there could be 20 or more unique products.
The value that is important to me is [product_code]. You can see that in the first array, there is [product_code] => HL102668. In the second there is [product_code] => HD245839.
How can I check to see if 'HD' exists in any of the [product_code] values? If it does, I need to return false.
Thank you for your help!
Access your sub array :
$products = $array['CART']['ITEMS'];
Loop through your sub array :
foreach ($products as $product)
Check if HD exists in your product_code, with either simple strstr, or with regex using preg_match (if you are comfortable with it).
if (strstr($product['product_code'], "HD")) {
// Do your actions
}

Categories