Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a array containing other arrays(sub arrays). I need to get index of subarray that consist specific value of a key. For example. Here is my array:
Array
(
[0] => Array
(
[id] => 353
[name] => account_2
[ips] =>
[tech_prefix] =>
[password] =>
[id_voip_hosts] =>
[proxy_mode] =>
[auth_type] => ani
[ani] => 526466
[accname] =>
[protocol] =>
[port] =>
[orig_enabled] => 1
[term_enabled] =>
[orig_capacity] =>
[term_capacity] =>
[orig_rate_table] =>
[term_rate_table] =>
[id_dr_plans] =>
[orig_groups] =>
[term_groups] =>
[notes] =>
)
[1] => Array
(
[id] => 352
[name] => account_3
[ips] =>
[tech_prefix] =>
[password] =>
[id_voip_hosts] =>
[proxy_mode] =>
[auth_type] => ani
[ani] => 1345436
[accname] =>
[protocol] =>
[port] =>
[orig_enabled] => 1
[term_enabled] =>
[orig_capacity] =>
[term_capacity] =>
[orig_rate_table] =>
[term_rate_table] =>
[id_dr_plans] =>
[orig_groups] =>
[term_groups] =>
[notes] =>
)
[2] => Array
(
[id] => 354
[name] => account_4
[ips] =>
[tech_prefix] =>
[password] =>
[id_voip_hosts] =>
[proxy_mode] =>
[auth_type] => ani
[ani] => 472367427
[accname] =>
[protocol] =>
[port] =>
[orig_enabled] => 1
[term_enabled] =>
[orig_capacity] =>
[term_capacity] =>
[orig_rate_table] =>
[term_rate_table] =>
[id_dr_plans] =>
[orig_groups] =>
[term_groups] =>
[notes] =>
)
)
What I need. For example I need to delete from the array subarray [2]. I know a way with unset($myarray[2]) but how can I get this index [2]. If I know only [ani] key value 472367427. How to get this "[2]" in var to insert it in unset command.
If I would need to delete subarray that have a key [ani] that is = 1345436(it is in array [1]). Is there a way to search index of array by value of a key.
Again, how to find this index [2] or [1] by [ani] key in multidimensional array?
Thanks!
I think this should work (not tested - but you get the idea)
foreach ($arrays as $key => $item)
{
if ($item['ani'] === '472367427')
{
unset($arrays[$key]);
}
}
There are several ways of going about this, but array_filter is probably the most scalable. You will need to create a callback function which searches for values you want to get rid of and then use it as the filter for the array:
function filterCallback($value) {
if($value['ani'] == "472367427") {
return false;
} else {
return true;
}
}
$array = array_filter($array,'filterCallback');
The advantage to this is that you can abstract your filtering logic (and make it more complex) without having to do it within a foreach loop.
See http://www.php.net/manual/en/function.array-filter.php
$remove = 472367427;
foreach($your_array as $key => $values) {
if(!empty($values['ani'] && $values['ani'] == $remove) {
unset($your_array[$key]);
}
}
If you already know the ani value you are looking for:
$yourani = 'Your known ani value';
foreach($myarray AS $array){
if($array['ani'] == $yourani){
unset($array);
}
}
You can use array_search to get the index and unset the element like this
$a = array('one', 'two', 'three', 472367427, 'four', 'five');
unset($a[array_search(472367427, $a)]);
Related
i want array_diff using this code i am also getting output but same time error occur
"Array to string conversion"
I am using codeigniter, i am getting post value in second array(listingdata) with method $this->input->post(); , but my first array getting some dynamic key and value then this two array diff give me output but some time getting error.
Please Help me
Any solution always welcome.
if(isset($_POST)){
foreach($_POST as $key => $value) {
$arr[$key] = $value; // making array
}
}
$result = array_diff($arr,$listingdata);
print_r($result);
print_r($arr);
print_r($listingdata);
My $arr array
Array
(
[itemTitle] => fdafdas
[subtitle] => fadsfdas
[quantity] => 12
[itemDescription] => fdas
[hide_ebay_id] => 89
[ebay_user] => Array
(
[0] =>
)
[ebay_category] => 2984
[e_sub_cat] => 20433
[e_second_child_sub_cat] => 117027
[e_third_child_sub_cat] =>
[ebay_upc] => 31231241341
[Brand] => Unbranded
[MPN] => Does_Not_Apply
[Model] => fsdf
[Country/Region_of_Manufacture] => Unknown
[listingType] => FixedPriceItem
[listingduration] => Days_5
[buy_it_now_price] => 20.00
[shippingtype] => Flat
[fshippingservice] => USPSPriorityFlatRateBox
[shippingservicecost] => 2.0
[shippingsac] => 3.0
[internationalhc] =>
[paypalemailaddress] => sam#jaff.in
[dispatchtimemax] => 3
[location] => CA
[ebaycountry] =>
[ebay_paypalemail] =>
[ReturnsAccepted] => ReturnsAccepted
[returnswithin] => Days_14
[refundoption] => MoneyBack
[shippingcostpaidbyoption] => Seller
[policydescription] => wqdewvfdgbfdggrbf
)
This is my another Array
Array
(
[itemTitle] => fdafdas
[subTitle] => fadsfdas
[categoryId] => 117027
[itemDescription] => fdas
[listingType] => FixedPriceItem
[listingDuration] => Days_5
[startPrice] =>
[buyItNowPrice] => 20.00
[quantity] => 12
[upc] => 31231241341
[paypalEmailAddress] => sam#jaff.in
[returnWithin] => Days_14
[RefundOption] => MoneyBack
[ShippingCostPaidByOption] => Seller
[returnsAccepted] => ReturnsAccepted
[shippingType] => Flat
[cshippingService] =>
[fshippingService] => USPSPriorityFlatRateBox
[dcPostalcode] =>
[ShippingServiceCost] => 2.0
[dshippingPackage] =>
[shippingHandlingcost] =>
[shippingServiceAdditionalCost] => 3.0
[currency] => USD
[country] =>
[location] => CA
[dispatchTimeMax] => 3
[pictureUrl] => Array
(
[0] => http://jaftech.in/ashprey/uploads/69.jpg
)
[policyDescription] => wqdewvfdgbfdggrbf
[internationalShipping] =>
[internationalShippingType] =>
[internationalShippingServiceCost] =>
[internationalshippingServiceAdditionalCost] =>
[cinternationalshippingService] =>
[finternationalshippingService] =>
[internationalShipToLocation] =>
[internationaloriginatingPostalCode] =>
[internationalshippingHandlingcost] =>
[ishippingPackage] => PackageThickEnvelope
[pid] => 89
)
This is because array_diff compares values after typecasting both compared values to string (see documentation notes).
Both of your arrays contain another array (ebay_user and second pictureUrl).
See this answer for recursive array_diff, which should work in your case.
I am fairly new to PHP and I am writing a PHP function that grabs an object from SOAP.
I found a code to convert it to an array but I can't manage to echo any data.
The array from print_r
Array
(
[Status] => Array
(
[Code] => 0
[Message] => OK
)
[Order] => Array
(
[OrderNumber] => 9334543
[ExternalOrderNumber] =>
[OrderTime] => 2014-07-15T15:20:31+02:00
[PaymentMethod] => invoice
[PaymentStatus] => Paid
[ShipmentMethod] => Mypack
[DeliveryStatus] => Delivered
[Language] => sv
[Customer] => Array
(
[CustomerId] => 13556
[CustomerNumber] =>
[Username] => admin
[Approved] => 1
[OrgNumber] => 9309138445
[Company] =>
[VatNumber] =>
[FirstName] => Jane
[LastName] => Doe
[Address] => Gatan
[Address2] =>
[Zip] => 1230
[City] => Staden
[Country] => Sweden
[CountryCode] => SE
[PhoneDay] => 84848474
[PhoneNight] =>
[PhoneMobile] =>
[Email] => mail#msn.com
[NewsLetter] =>
[OrgType] => person
[OtherDelivAddress] =>
[DelivName] =>
[DelivAddress] =>
[DelivAddress2] =>
[DelivZip] =>
[DelivCity] =>
[DelivCountry] =>
[DelivCountryCode] =>
)
[Comment] =>
[Notes] => 9063025471 UK/MA
[CurrencyCode] => SEK
[ExchangeRate] => 1
[LanguagePath] => se
[FreightWithoutVat] => 0
[FreightWithVat] => 0
[FreightVatPercentage] => 25
[PayoptionFeeWithoutVat] => 0
[PayoptionFeeWithVat] => 0
[PayoptionFeeVatPercentage] => 25
[CodWithoutVat] => 0
[CodWithVat] => 0
[CodVatPercentage] => 0
[DiscountWithoutVat] => 0
[DiscountWithVat] => 0
[DiscountVat] => 0
[TotalWithoutVat] => 4388
[TotalWithVat] => 5485
[TotalVat] => 1097
[PayWithoutVat] =>
[AffiliateCode] =>
[AffiliateName] =>
[OrderField] => Array
(
[0] => Array
(
[Name] => external_ref
[Value] => 43445
)
[1] => Array
(
[Name] => webshopid
[Value] => 423
)
[2] => Array
(
[Name] => webshopname
[Value] => Manuell
)
)
)
)
Non working code
echo $array[1][0]
I have tried different combos of indexes. I know how to return the values from the soap object but if I could do it this way it would be easier. It should work shouldn't it?
$array[1] is the second index of the array. the key of this array us "Status", this array contains a code and message
i assume you want to echo the message, you can do that with the following
echo $array[1]["Status"]["Message"];
You should use $array['Status']['Code'] , $array['Status']['Message'], $array['Order']['OrderNumber'], $array['Order']['Customer']['CustomerId'] and so on to display your data. It's an associative array so you need to use string keys and not numbers
try
$array['Order']['Customer']['LastName']
is my best guess without losing my sanity in that one line.
But for us to be sure please post the print_r($array) output
There are some way I always do this:
print_r($array);
And the other way is
$array[0]['Order']['LastName']
Try to access the arrays elements with the string keys, not the integer ones you are using:
echo $array['Order']['Customer']['Address'];
Another way you could see what is going on is by iterating through the array, and print out the keys and values:
foreach ($array as $key => $value)
echo "Key=$key value=$value<br>";
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I have an php array
Array
(
[results] => Array
(
[0] => Array
(
[birthday] => 11-Apr-2014
[category] => Array
(
[0] => 204
[1] => 300
[2] => 304
)
[city] => Dhaka
[country] => Bangladesh
[email] => javaorjava#gmail.com
[fullName] => biplob
[gender] => Male
[inspirational] => Run to dream
[phone] => aapbd1
[photo] => Array
(
[__type] => File
[name] => 8bef9bc3-ee64-45df-9698-0466e255c1bd-profilePhoto.jpg
[url] => http://files.com/c2dcf728-e2a3-4b2d-a8c8-6ec9b3c6502a/8bef9bc3-ee64-45df-9698-0466e255c1bd-profilePhoto.jpg
)
[username] => aapbd
[website] => http://ss.com
[createdAt] => 2014-04-10T19:01:16.396Z
[updatedAt] => 2014-04-28T07:36:18.459Z
[objectId] => IQSCdXE2hI
)
[1] => Array
(
[birthday] => 09-Apr-1982
[category] => Array
(
[0] => 204
[1] => 307
[2] => 311
[3] => 313
[4] => 102
[5] => 103
[6] => 105
[7] => 107
)
[city] => Madrid
[country] => Spain
[coverPhoto] => Array
(
[__type] => File
[name] => aa53cf65-47af-464d-aa49-88202f91388f-coverPhoto.jpg
[url] => http://files.com/c2dcf728-e2a3-4b2d-a8c8-6ec9b3c6502a/aa53cf65-47af-464d-aa49-88202f91388f-coverPhoto.jpg
)
[description] => a lazy man
[email] => skio#yahoo.com
[fullName] => Sjun
[gender] => Male
[inspirational] => Honesty is the best policy
[phone] => 135469
[photo] => Array
(
[__type] => File
[name] => a1aec283-f3c7-484c-a8b2-a0b09c5f3023-profilePhoto.jpg
[url] => http://files.com/c2dcf728-e2a3-4b2d-a8c8-6ec9b3c6502a/a1aec283-f3c7-484c-a8b2-a0b09c5f3023-profilePhoto.jpg
)
[username] => asa
[website] =>
[createdAt] => 2014-04-09T07:58:19.043Z
[updatedAt] => 2014-05-07T11:13:40.671Z
[objectId] => iVb6olefaT
)
)
)
I'm trying to practice/learn foreach loops in PHP. I understand basic foreach. But I struggle with multi-dimensionals.
I want to get my every array birthday,photo name,photo url,category.
But I cant retrieve those correctly with foreach loop
Use a simple foreach() for iterating over MD arrays..
foreach($yourarray['results'] as $k=>$arr)
{
echo $arr['birthday'];
echo $arr['photo']['name'];
echo $arr['photo']['url'];
}
Let's say your array is $data,
foreach ($data['results'] as $key => $value)
echo $value['birthday'];
echo $value['photo']['name'];
echo $value['photo']['url'];
}
use $key as index value.
This is how you can access your nested array, regardless the amount of categories:
// Loop over all elements of main array element
foreach($array['results'] as $arr_key => $arr_value) {
// Loop over children
foreach($arr_value as $key => $value) {
// Element is array (like 'category' or 'photo')
if(is_array($value)) {
foreach($value as $sub_key => $sub_value) {
echo $key."[".$sub_key."] = ".$sub_value;
}
// Element is no array
} else {
echo $key." = ".$value;
}
}
}
(Example)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have array
Array
(
[0] => Array
(
[question_summary] =>
[answer1] => 18
[answer2] => 3
[PercentEVQ] => 10.8000
[PercentEVQ2] => 11
[driver_display_name] => Position
[cluster_name] => Personal Impact
)
[1] => Array
(
[question_summary] =>
[answer1] => 51
[answer2] => 3
[PercentEVQ] => 30.6000
[PercentEVQ2] => 31
[driver_display_name] => Position
[cluster_name] => Personal Impact
)
)
how to create new array become
Array
(
[Personal Impact] => Array
(
[Position] => array
(
[0] => array
(
[question_summary] =>
[answer1] => 18
[answer2] => 3
[PercentEVQ] => 10.8000
[PercentEVQ2] => 11
[driver_display_name] => Position
[driver_name] => Position
[cluster_name] => Personal Impact
)
[1] => Array
(
[question_summary] =>
[answer1] => 51
[answer2] => 3
[PercentEVQ] => 30.6000
[PercentEVQ2] => 31
[driver_display_name] => Position
[driver_name] => Position
[cluster_name] => Personal Impact
)
)
)
)
Is it possible?
Yes it's possible you can just foreach(your values as key => value) {} it or something like this:
Sample Fiddle
<?php
$new_values = array();
foreach($old_values as $key => $values) {
$new_values[$values['cluster_name']][$values['driver_display_name']][] = array(
'answer1' => $values['answer1'],
'answer2' => $values['answer2'],
'PercentEVQ' => $values['PercentEVQ'],
'PercentEVQ2' => $values['PercentEVQ2'],
'driver_display_name' => $values['driver_display_name'],
'cluster_name' => $values['cluster_name'],
);
}
Are you defining a new array?
$new_array['Personal Impact']['Position'] = $old_array;
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have an array:
Array
(
[0] => Array
(
[id] => 31299
[name] => 37322426212
[ips] =>
[tech_prefix] =>
[password] =>
[id_voip_hosts] =>
[proxy_mode] =>
[auth_type] => ani
[ani] => 37322426212
[accname] =>
[protocol] =>
[port] =>
[orig_enabled] => 1
[term_enabled] =>
[orig_capacity] =>
[term_capacity] =>
[orig_rate_table] => 7
[term_rate_table] =>
[id_dr_plans] =>
[orig_groups] =>
[term_groups] =>
[notes] =>
)
[1] => Array
(
[id] => 4373
[name] => 37322983029
[ips] =>
[tech_prefix] =>
[password] =>
[id_voip_hosts] =>
[proxy_mode] =>
[auth_type] => ani
[ani] => 37322983029
[accname] =>
[protocol] =>
[port] =>
[orig_enabled] => 1
[term_enabled] =>
[orig_capacity] =>
[term_capacity] =>
[orig_rate_table] => 7
[term_rate_table] =>
[id_dr_plans] =>
[orig_groups] =>
[term_groups] =>
[notes] =>
)
[2] => Array
(
[auth_type] => ani
[name] => 37322983029
[ani] => 37322983029
[orig_enabled] => Array
(
[0] => on
)
[orig_rate_table] => 7
)
)
Items with 0,1,2 may be more(3,4...10...and so on).
What I am trying to do is to find array with key ani and name = 37322983029 and replace
name with '###' and ani to empty:
[mane]=>"###",//where name = '37322983029'
[ani]=> //where ani = '37322983029'
I tried with str_replace but no success.
How can this be done?
I think, this is what you are looking for:
foreach($yourArray as &$a)
{
if($a["ani"] == 37322983029 and $a["ani"] == $a["name"])
{
$a["name"] = "###";
$a["ani"] = "";
}
}
Not sure how you were using str_replace, but the following should work (assuming that ani and mane (or name?) are actually string indices into your array - not obvious from your example):
foreach($myArray as &$val) {
if($val['ani'] == 37322983029) {
$val['ani'] = '';
$val['name'] = "###";
}
}
important Note the use of & to pass the value by reference so you are working with actual elements of the array, not copies... In that way, when you modify $val you are actually modifying the original array. Without the ampersand, your initial array would be unchanged by the loop.
Also note - it is not clear from your example whether you want to test for just ani==37322983029 or also for name=37322983029. I am sure you can modify the code above to have both conditions (or see Alexxus's answer)
A complete code example (tested, working):
<?php
$a = Array(Array('a'=>4, 'b'=>5),Array('a'=>6, 'b'=>7));
echo '<pre>';
print_r($a);
foreach($a as &$v){
if($v['a']==6) {
$v['a'] = 12;
$v['b'] = '';
}
}
print_r($a);
echo '</pre>';
?>
Produces output
Array
(
[0] => Array
(
[a] => 4
[b] => 5
)
[1] => Array
(
[a] => 6
[b] => 7
)
)
Array
(
[0] => Array
(
[a] => 4
[b] => 5
)
[1] => Array
(
[a] => 12
[b] =>
)
)