Multidimensional array value if exits - php

I want to bring results that have a status 1 in the array.(Sorry i don't speak english)
My array is;
[10100002] => Array
(
[0] => stdClass Object
(
[ID] => 664
[barcode] => 10100002
[status] => 0
)
[1] => stdClass Object
(
[ID] => 1339
[barcode] => 10100002
[status] => 0
)
)
[10100004] => Array
(
[0] => stdClass Object
(
[ID] => 1116
[barcode] => 10100004
[status] => 1
)
[1] => stdClass Object
(
[ID] => 1826
[barcode] => 10100004
[status] => 0
)
)
in 10100002 two status is 0 but second array found status 1. if the status value is 1 in multiple arrays i like result this ;
[10100004] => Array
(
[0] => stdClass Object
(
[ID] => 1116
[barcode] => 10100004
[status] => 1
)
[1] => stdClass Object
(
[ID] => 1826
[barcode] => 10100004
[status] => 0
)
)
My code is here;
$result = array();
foreach ($fetch_data as $value) {
if($value->status== 1)
$result[$value->barcode][] = $value;
}
// this give me only one result. Output;
[10100004] => Array
(
[0] => stdClass Object
(
[ID] => 1116
[barcode] => 10100004
[status] => 1
)
)

You can use array_walk
$arr = Array(
'10100002' => Array
(
'0' => Array
(
'ID' => 664,
'barcode' => 10100002,
'status' => 0
),
'1' => Array
(
'ID' => 1339,
'barcode' => 10100002,
'status' => 0
)
),
'10100004' => Array
(
'0' => Array
(
'ID' => 1116,
'barcode' => 10100004,
'status' => 1
),
'1' => Array
(
'ID' => 1826,
'barcode' => 10100004,
'status' => 0
)
)
);
$res = [];
array_walk($arr, function($v, $k) use (&$res){
foreach($v as $key => $value){
if($value['status']){
!empty($value['status']) ? ($res[$k][] = (object)$v[$key]) : '';
}
}
});
echo '<pre>';
print_r($res);
Output
Array
(
[10100004] => Array
(
[0] => stdClass Object
(
[ID] => 1116
[barcode] => 10100004
[status] => 1
)
)
)
LIVE DEMO

Related

Laravel - How can I add new array key with value to the collection output

I have this query:
$get_products = Cache::rememberForever('all_imports', function () use ($collection) {
return DB::connection('mongodb')->collection( $collection )->paginate( self::NO_OF_PRODUCTS );
});
If I print_r this output:
echo '<pre>';
print_r( $get_products );
echo '</pre>';
I got this request:
Illuminate\Pagination\LengthAwarePaginator Object
(
[items:protected] => Illuminate\Support\Collection Object
(
[items:protected] => Array
(
[0] => Array
(
[_id] => MongoDB\BSON\ObjectId Object
(
[oid] => 639e0f59889929ce620f4e9c
)
[id] => 35035
[availability] => In stock
[brand] => Bogas Primavara Vara
[condition] => new
[date_add] => 1671303001
[date_upd] => 1673865782
[description] => Rochie dama scurta catifea neagra Antonietta Bogas Rochie dama scurta catifea neagra Antonietta Bogas
[image_link] => https://www.bogas.ro/continut/produse/35035/1000/rochie-dama-scurta-catifea-neagra-antonietta-bogas_126777.jpeg
[link] => https://www.bogas.ro/rochie-dama-scurta-catifea-neagra-antonietta-bogas/?utm_source=googlemerchantcenter&utm_medium=cpc&utm_campaign=direct_link
[price] => 229.99 RON
[product_type] => Rochii
[sale_price] => 149.99 RON
[title] => Rochie dama scurta catifea neagra Antonietta Bogas
[update_history] => Array
(
[0] => Array
(
[id_feed] => 269
[feed_name] => bogas direct
[date_upd] => 1673865782
[field_history] => Array
(
)
)
)
[all_sizes] => Array
(
[0] => XS
[1] => S
[2] => M
[3] => L
[4] => XL
)
[sizes_out_of_stock] => Array
(
)
[additional_image_link] => Array
(
[0] => https://www.bogas.ro/continut/produse/35035/520/rochie-dama-scurta-catifea-neagra-antonietta-bogas_126775.jpeg
[1] => https://www.bogas.ro/continut/produse/35035/520/rochie-dama-scurta-catifea-neagra-antonietta-bogas_126776.jpeg
)
[all_attributes] => Array
(
[0] => Negru
[1] => Negru
[2] => Negru
[3] => Negru
[4] => Negru
)
[ean13] =>
[in_stock_attributes] => Array
(
[0] => Negru
[1] => Negru
[2] => Negru
[3] => Negru
[4] => Negru
)
[specs] => Array
(
[Material] => Catifea
)
[total_optiuni_out_of_stock] => Array
(
)
[clicks_last_30days_present] => 0
[field_update] => Array
(
[clicks_last_30days_present] => 1673872147
[cost_last_30days_present] => 1673872147
[conversions_last_30days_present] => 1673872147
[conversions_value_last_30days_present] => 1673872147
[impressions_last_30days_present] => 1673872147
[roas_last_30days_present] => 1673872147
)
[cost_last_30days_present] => 0
[conversions_last_30days_present] => 0
[conversions_value_last_30days_present] => 0
[impressions_last_30days_present] => 4
[roas_last_30days_present] => 0
)
)
[escapeWhenCastingToString:protected] =>
)
[perPage:protected] => 1
[currentPage:protected] => 1
[path:protected] => http://127.0.0.1:8000/api/price-monitor/matching/your-product/97-0048-2571-870/1
[query:protected] => Array
(
)
[fragment:protected] =>
[pageName:protected] => page
[onEachSide] => 3
[options:protected] => Array
(
[path] => http://127.0.0.1:8000/api/price-monitor/matching/your-product/97-0048-2571-870/1
[pageName] => page
)
[total:protected] => 830
[lastPage:protected] => 830
)
Now, I want to added a new array key with value to the output. So, I am doing this:
if( isset( $get_products[0]['additional_image_link'] ) && ! empty( $get_products[0]['additional_image_link'] ) ) {
$get_products[0]['carousel_images'] = $get_products[0]['additional_image_link'];
}
But I got an error message :
Indirect modification of overloaded element of
Illuminate\Pagination\LengthAwarePaginator has no effect

How do I get the array block from within the array?

I want to convert the xml data that I have generated from my system into an array array and send it to the API system of the platform I sell individually.
I'd appreciate it if you could review and support.
my array data example:
Array
(
[product] => Array
(
[0] => Array
(
[productSellerCode] => bebe27
[title] => Uzun Kollu Renkli Uyku Tulum Body Zıbın 6 Aylık Bebek
[subtitle] => Stoktan hızlı kargo
[description] => Bebeğiniz İçin Özel Günlerde ve Günlük Olarak Kullanabileceği Mükemmel Takım.Kaliteli Şık ve Zarif Olan Bu Ürünü Sizlere Sunuyoruz.%100 Pamuk olan bu ürünü Bebeğinize Güvenle Giydirebilirsiniz Dokusu Yumuşaktır.
[category] => Array
(
[id] => 1000053
)
[price] => 48.472
[domestic] => false
[currencyType] => 1
[images] => Array
(
[image] => Array
(
[url] => https://tuccar.com.tr/image/catalog/bebe/IMG_7976.JPG
[order] => 1
)
)
[attributes] => Array
(
[attribute] => Array
(
[0] => Array
(
[name] => Beden
[value] => 3-6 Ay
)
[1] => Array
(
[name] => Marka
[value] => DİĞER
)
)
)
[saleStartDate] => Array
(
)
[saleEndDate] => Array
(
)
[productionDate] => Array
(
)
[expirationDate] => Array
(
)
[productCondition] => 1
[preparingDay] => 2
[discount] => Array
(
[startDate] => Array
(
)
[endDate] => Array
(
)
[type] => Array
(
)
[value] => Array
(
)
)
[shipmentTemplate] => kargo-bizden
[stockItems] => Array
(
[stockItem] => Array
(
[quantity] => 1
[sellerStockCode] => Array
(
)
[attributes] => Array
(
[attribute] => Array
(
[name] => Array
(
)
[value] => Array
(
)
)
)
[optionPrice] => Array
(
)
)
)
)
[1] => Array
(
[productSellerCode] => MS-S010
[title] => 10 cm Samur Kase
[subtitle] => Stoktan hızlı kargo
[description] => Ölçü: 10 cmÜlkemizde, el işçiliği şeklinde üretilmiştir.
[category] => Array
(
[id] => 1016108
)
[price] => 31.426
[domestic] => false
[currencyType] => 1
[images] => Array
(
[image] => Array
(
[url] => https://tuccar.com.tr/image/catalog/MS/MS-S009-1.jpg
[order] => 1
)
)
[attributes] => Array
(
[attribute] => Array
(
[0] => Array
(
[name] => Marka
[value] => DİĞER
)
[1] => Array
(
[name] => Materyal
[value] => Seramik
)
)
)
[saleStartDate] => Array
(
)
[saleEndDate] => Array
(
)
[productionDate] => Array
(
)
[expirationDate] => Array
(
)
[productCondition] => 1
[preparingDay] => 3
[discount] => Array
(
[startDate] => Array
(
)
[endDate] => Array
(
)
[type] => Array
(
)
[value] => Array
(
)
)
[shipmentTemplate] => kargo-bizden
[stockItems] => Array
(
[stockItem] => Array
(
[quantity] => 10
[sellerStockCode] => Array
(
)
[attributes] => Array
(
[attribute] => Array
(
[name] => Array
(
)
[value] => Array
(
)
)
)
[optionPrice] => Array
(
)
)
)
)
I want to post an array block here every time.
(
[productSellerCode] => MS-S010
[title] => 10 cm Samur Kase
[subtitle] => Stoktan hızlı kargo
[description] => Ölçü: 10 cmÜlkemizde, el işçiliği şeklinde üretilmiştir.
[category] => Array
(
[id] => 1016108
)
[price] => 31.426
[domestic] => false
[currencyType] => 1
[images] => Array
(
[image] => Array
(
[url] => https://tuccar.com.tr/image/catalog/MS/MS-S009-1.jpg
[order] => 1
)
)
[attributes] => Array
(
[attribute] => Array
(
[0] => Array
(
[name] => Marka
[value] => DİĞER
)
[1] => Array
(
[name] => Materyal
[value] => Seramik
)
)
)
[saleStartDate] => Array
(
)
[saleEndDate] => Array
(
)
[productionDate] => Array
(
)
[expirationDate] => Array
(
)
[productCondition] => 1
[preparingDay] => 3
[discount] => Array
(
[startDate] => Array
(
)
[endDate] => Array
(
)
[type] => Array
(
)
[value] => Array
(
)
)
[shipmentTemplate] => kargo-bizden
[stockItems] => Array
(
[stockItem] => Array
(
[quantity] => 10
[sellerStockCode] => Array
(
)
[attributes] => Array
(
[attribute] => Array
(
[name] => Array
(
)
[value] => Array
(
)
)
)
[optionPrice] => Array
(
)
)
)
)
I think I'm making a mistake in foreach operations.
I can send 1 product as below, I need to send all products in order.
<?php
include "class.n11.php";
$n11Params = [
'appKey' => 'my-api-key',
'appSecret' => 'my-api-secret'
];
$n11 = new N11($n11Params);
$xmlfile = file_get_contents("https://tuccar.com.tr/API/n11/100urun.php");
$new = simplexml_load_string($xmlfile);
$con = json_encode($new,JSON_UNESCAPED_UNICODE);
$newArr = json_decode($con, true);
foreach ($newArr as &$urun) {
$productSellerCode = $urun[$i]->productSellerCode;
$title = $urun[$i]->title;
$description = $urun[$i]->description;
$categoryid = $urun[$i]->category->id;
$price = $urun[$i]->price;
$preparingDay = $urun[$i]->preparingDay;
$quantity = $urun[$i]->quantity;
$saveProduct = $n11->SaveProduct(
[
'productSellerCode' => $productSellerCode,
'title' => $title,
'subtitle' => 'Stoktan hızlı kargo',
'description' => $description,
'category' =>
[
'id' => $categoryid
],
'attributes' =>
[
'attribute' =>
foreach($urun->attributes as $attribute){
'name' => $attribute['name'],
'value' => $attribute['value']
}
],
'price' => $price,
'domestic' => false,
'currencyType' => 'TL',
'images' =>
[
'image' =>
foreach($urun->images as $image){
'url' => $image['url'],
'order' => $image['order']
}
],
'saleStartDate' => '',
'saleEndDate' => '',
'productionDate' => '',
'expirationDate' => '',
'productCondition' => '1',
'preparingDay' => $preparingDay,
'discount' => '',
'shipmentTemplate' => 'kargo-bizden',
'stockItems' =>
[
'stockItem' =>
[
'quantity' => $quantity,
'sellerStockCode' => '',
'attributes' =>
[
'attribute' => []
],
'optionPrice' => ''
]
]
]
);
} var_dump($saveProduct);
#RiggsFolly, It worked that way yes but only the first ranked product was sent. I couldn't do the loop.
<?php
include "class.n11.php";
$n11Params = ['appKey' => 'my-api-key', 'appSecret' => 'my-api-secret'];
$n11 = new N11($n11Params);
$xmlfile = file_get_contents("https://tuccar.com.tr/API/n11/100urun.php");
$new = simplexml_load_string($xmlfile);
$con = json_encode($new,JSON_UNESCAPED_UNICODE);
$newArr = json_decode($con, true);
foreach ($newArr['product'] as $product) {
$saveProduct = $n11->SaveProduct($product);
}
var_dump($saveProduct);
I succeeded with the following code.
var_dump($products);
foreach($products as $indis=>$degeri){
foreach($degeri as $icindekiler){
$saveProduct = $n11->SaveProduct($icindekiler);
}
}
var_dump($saveProduct);
simply start you foreach one step down into the array i.e. from $newArr['product'] and each array you process from there will be the array you want to pass as the parameter.
foreach ($newArr['product'] as $product) {
$saveProduct = $n11->SaveProduct($product);
}
Also this may or may not actually exist in your real code but this array is not correctly coded, it has a missing '
$n11Params = [
'appKey' => 'my-api-key', // missing quote added
'appSecret' => 'my-api-secret'
];

PHP array merge to subarray with keys

I have a problem with merging array's. I'll try array merge and combine but nothing is working.
First array
Array (
[type1] => Array (
[userid] => Array (
[0] => 35
[1] => 37
)
[from] => Array (
[0] => 07-06-2017
[1] => 09-06-2017
)
[till] => Array (
[0] => 07-07-2017
[1] => 09-07-2017
)
)
[type3] => Array (
[userid] => Array (
[0] => 13
)
[from] => Array (
[0] => 10-06-2017
)
[till] => Array (
[0] => 10-07-2017
)
)
)
Second array
The second array is filled with room details, but the assigned users are not added yet.
Array (
[type1] => Array (
[m2] =>
[price] =>
[rooms] => 1
[extra] =>
[rented_to] => Array
(
[0] => Array
(
[userid] =>
[from] =>
[till] =>
)
)
)
[type3] => Array
(
[m2] =>
[price] =>
[rooms] => 1
[extra] =>
[rented_to] => Array
(
[0] => Array
(
[userid] =>
[from] =>
[till] =>
)
)
)
)
I'll will put these arrays together to one array, so that the data is insert into the "rented_to" section. How can I get this array into an another array like this:
Array (
[type1] => Array (
[m2] =>
[price] =>
[rooms] => 1
[extra] =>
[rented_to] => Array
(
[0] => Array
(
[userid] => 35
[from] => 07-06-2017
[till] => 07-07-2017
)
[1] => Array
(
[userid] => 37
[from] => 09-06-2017
[till] => 09-07-2017
)
)
)
[type3] => Array
(
[m2] =>
[price] =>
[rooms] => 1
[extra] =>
[rented_to] => Array
(
[0] => Array
(
[userid] => 13
[from] => 10-06-2017
[till] => 10-07-2017
)
)
)
)
The code
$manager_add_new_room_rented_to is an array that contains the value of the first array in my example.
$manager_add_new_room_type_desc = $_POST['manager_add_new_room_type_desc'];
$manager_add_new_room_type_m2 = $_POST['manager_add_new_room_type_m2'];
$manager_add_new_room_type_rent_price = $_POST['manager_add_new_room_type_rent_price'];
$manager_add_new_room_type_rooms = $_POST['manager_add_new_room_type_rooms'];
$manager_add_new_room_type_extra = $_POST['manager_add_new_room_type_extra'];
$manager_add_new_room_rented_to = $_POST['manager_add_new_room_rented_to'];
$add_new_room_information = array();
foreach ( $manager_add_new_room_type_desc as $key => $room_type ) :
$add_new_room_information[$room_type] = array(
'm2' => $manager_add_new_room_type_m2[$key],
'price' => $manager_add_new_room_type_rent_price[$key],
'rooms' => $manager_add_new_room_type_rooms[$key],
'extra' => $manager_add_new_room_type_extra[$key],
'rented_to' => array(
array(
'userid' => '',
'from' => '',
'till' => ''
)
)
);
endforeach;
Loop through $manager_add_new_room_rented_to[$room_type] and create the new array that you want.
foreach ( $manager_add_new_room_type_desc as $key => $room_type ) :
$renters = $manager_add_new_room_rented_to[$room_type];
$rented_to = array();
foreach ($renters['userid'] as $index => $userid) :
$rented_to[] = array('userid' => $userid, 'from' => $renters['from'][$index], 'to' => $renters['to'][$index]);
endforeach;
$add_new_room_information[$room_type] = array(
'm2' => $manager_add_new_room_type_m2[$key],
'price' => $manager_add_new_room_type_rent_price[$key],
'rooms' => $manager_add_new_room_type_rooms[$key],
'extra' => $manager_add_new_room_type_extra[$key],
'rented_to' => $rented_to
)
);
endforeach;

Converting a php object into associative array

I am trying to read the following php object result of an api call into an associative array. Has someone done this before or can otherwise help me?
I have tried object var dump, and array casting, but this just doesnt seems to work. I know I am doing something fundamentally wrong. Can someone help?
Many thanks.
Google_Service_Directory_Users Object
(
[etag] => "sfgsfgdsfgsdfgjkdjgfd"
[kind] => admin#directory#users
[nextPageToken] =>
[triggerEvent] =>
[usersType:protected] => Google_Service_Directory_User
[usersDataType:protected] => array
[collection_key:protected] => items
[modelData:protected] => Array
(
[users] => Array
(
[0] => Array
(
[kind] => admin#directory#user
[id] => 7642341239423
[etag] => "jasdfjshwer43537345fsdfs"
[primaryEmail] => info#example.com
[name] => Array
(
[givenName] => Info -
[familyName] => Example
[fullName] => Info - Example
)
[isAdmin] =>
[isDelegatedAdmin] =>
[lastLoginTime] => 2014-07-29T08:46:28.000Z
[creationTime] => 2014-07-29T08:31:56.000Z
[agreedToTerms] => 1
[suspended] =>
[changePasswordAtNextLogin] =>
[ipWhitelisted] =>
[emails] => Array
(
[0] => Array
(
[address] => info#example.com
[primary] => 1
)
)
[nonEditableAliases] => Array
(
[0] => info#example.com.test-google-a.com
)
[customerId] => fsdfdd4
[orgUnitPath] => /
[isMailboxSetup] => 1
[includeInGlobalAddressList] => 1
)
[1] => Array
(
[kind] => admin#directory#user
[id] => 3895729453245
[etag] => "fsajdfd64hkj4534h5k3454"
[primaryEmail] => user#example.com
[name] => Array
(
[givenName] => User
[familyName] => Name
[fullName] => User Name
)
[isAdmin] => 1
[isDelegatedAdmin] =>
[lastLoginTime] => 2014-08-26T09:05:49.000Z
[creationTime] => 2012-09-16T08:55:26.000Z
[agreedToTerms] => 1
[suspended] =>
[changePasswordAtNextLogin] =>
[ipWhitelisted] =>
[emails] => Array
(
[0] => Array
(
[address] => support#example.com
)
[1] => Array
(
[address] => help#example.com
)
)
[customerId] => fsdafwr4
[orgUnitPath] => /
[isMailboxSetup] => 1
[includeInGlobalAddressList] => 1
)
)
)
[processed:protected] => Array
(
)
)
First solution:
$array = json_decode(json_encode($nested_object), true);
Second solution:
function object_to_array($data) {
if (is_array($data) || is_object($data)):
$result = array();
foreach ($data as $key => $value)
$result[$key] = object_to_array($value);
return $result;
endif;
return $data;
}
both searched from the internetz

adding up value of array and getting the average

I have an array that looks similar to this,
[4] => Common_Model Object
(
[id] => 4
[name] =>
[date_created] =>
[last_updated] =>
[user_id_updated] =>
[_table] =>
[_aliases] => Array
(
[id] => 4
[name] =>
[date_created] =>
[date_updated] =>
[user_id_updated] =>
[rating] => 3
[recipe_id] => 5
)
[_nonDBAliases] => Array
(
)
[_default] => Array
(
)
[_related] => Array
(
)
[_enums] =>
[_alsoDelete] => Array
(
)
[_readOnly] => Array
(
[0] => date_updated
)
[_valArgs] => Array
(
)
[_valArgsHash] => Array
(
[default] => Array
(
)
)
[_valAliases] => Array
(
)
[_extraData] => Array
(
)
[_inputs] => Array
(
)
[_tableName] => jm_ratings
[_tablePrefix] =>
[_niceDateUpdated] => 1st Jan 70
[_niceDateCreated] => 1st Jan 70
[_fetchAdminData] =>
[_mCache] =>
[_assets] => Array
(
)
)
[3] => Common_Model Object
(
[id] => 3
[name] =>
[date_created] =>
[last_updated] =>
[user_id_updated] =>
[_table] =>
[_aliases] => Array
(
[id] => 3
[name] =>
[date_created] =>
[date_updated] =>
[user_id_updated] =>
[rating] => 1
[recipe_id] => 5
)
[_nonDBAliases] => Array
(
)
[_default] => Array
(
)
[_related] => Array
(
)
[_enums] =>
[_alsoDelete] => Array
(
)
[_readOnly] => Array
(
[0] => date_updated
)
[_valArgs] => Array
(
)
[_valArgsHash] => Array
(
[default] => Array
(
)
)
[_valAliases] => Array
(
)
[_extraData] => Array
(
)
[_inputs] => Array
(
)
[_tableName] => jm_ratings
[_tablePrefix] =>
[_niceDateUpdated] => 1st Jan 70
[_niceDateCreated] => 1st Jan 70
[_fetchAdminData] =>
[_mCache] =>
[_assets] => Array
(
)
)
[2] => Common_Model Object
(
[id] => 2
[name] =>
[date_created] =>
[last_updated] =>
[user_id_updated] =>
[_table] =>
[_aliases] => Array
(
[id] => 2
[name] =>
[date_created] =>
[date_updated] =>
[user_id_updated] =>
[rating] => 1
[recipe_id] => 5
)
[_nonDBAliases] => Array
(
)
[_default] => Array
(
)
[_related] => Array
(
)
[_enums] =>
[_alsoDelete] => Array
(
)
[_readOnly] => Array
(
[0] => date_updated
)
[_valArgs] => Array
(
)
[_valArgsHash] => Array
(
[default] => Array
(
)
)
[_valAliases] => Array
(
)
[_extraData] => Array
(
)
[_inputs] => Array
(
)
[_tableName] => jm_ratings
[_tablePrefix] =>
[_niceDateUpdated] => 1st Jan 70
[_niceDateCreated] => 1st Jan 70
[_fetchAdminData] =>
[_mCache] =>
[_assets] => Array
(
)
)
I wanting to add up the [rating] and get the mean average. But I dont know how do this with PHP, my attempt looks like this,
<?php
foreach ($rt as $rating) {
$total = $rating->rating + $rating->rating
}
$total / count($rt);
?>
Try this:
$total = 0;
foreach($rt as $elem) {
$total += $elem->_aliases['rating'];
}
echo sprintf("Average: %d", $total/count($rt));
<?php
$total = 0;
foreach ($rt as $obj) {
$total += $obj->_aliases['rating'];
}
print $total / count($rt);
?>

Categories