Replacing SimpleXMLObject objects by strings in array in PHP - php

I have an array with information that I get from the Amazon API and parsed it using SimpleXML. This gives me an array that looks like this :
[
[
0 => SimpleXMLElement Object (0 => B00TU53O8Q)
], [
0 => SimpleXMLElement Object (0 => B00TU53O8Q),
1 => SimpleXMLElement Object (0 => B015K13HWQ)
], [
0 => SimpleXMLElement Object (0 => B00TU53O8Q)
], [
...
]
]
Now, I want to convert this array to a more simplified format that no longer has any SimpleXML objects in them anymore.
Basically, I just want an array with only the strings they represent :
[
0 => B00TU53O8Q,
1 => B015K13HWQ,
2 => B00TU53O8Q,
1 => B00TU53O8Q
...
]
I then want to split that array into a 2-dimentional array, that looks something like this :
[
0 => [
0 => B00TU53O8Q
1 => B00TU53O8Q
2 => B015K13HWQ
3 => B00TU53O8Q
4 => B00TU53O8Q
],
1 => [
0 => B015K13HWQ
...
]
...
]
I don't know how to do this. Can you please help me?!

Here is a function to process your input:
function translate($data, &$result) {
if (is_array($data)) {
foreach($data as $element) {
translate($element, $result);
}
} else {
$result[] = (string) $data;
}
}
Call it like this:
// some test data:
$data = array(
array(
new SimpleXMLElement("<test>B00TU53O8Q</test>")
),
array(
new SimpleXMLElement("<test>B00TU53O8Q</test>"),
new SimpleXMLElement("<test>B015K13HWQ</test>")
),
array(
new SimpleXMLElement("<test>B00TU53O8Q</test>")
),
array(
new SimpleXMLElement("<test>B00TU53O8Q</test>"),
new SimpleXMLElement("<test>B015K13HWQ</test>")
)
);
$result = array();
translate($data, $result);
If you want to break up the $result array in chunks of 5, then proceed like this:
$chunks = array();
while (count($result)) {
$chuncks[] = array_slice($result, 0, 5);
$result = array_slice($result, 5);
}
print_r ($chuncks);
Ouput, based on test data, gives 2 chunks:
Array
(
[0] => Array
(
[0] => B00TU53O8Q
[1] => B00TU53O8Q
[2] => B015K13HWQ
[3] => B00TU53O8Q
[4] => B00TU53O8Q
)
[1] => Array
(
[0] => B015K13HWQ
)
)

right off the bat I think your if statement is wrong. Should be a double == if you are making a comparison. Essentially you are setting $asinValue equal to 'Asin Not Found' and it will evaluate true. It does not seem like you will ever get to the else portion of your code.

Related

How to add element to advanced array inside foreach loop

I am trying to add my data to my array inside my foreach loop.
I have almost done it successfully, except the array is too in-depth.
It's showing array->array->{WHAT I WANT}
When I need array->{WHAT I WANT}
Example, I'm needing it to be like:
Array
(
[home] => Array
(
[0] => Dashboard\Main#index
[1] => GET
)
[home/] => Array
(
[0] => Dashboard\Main#index
[1] => GET
)
)
When at the moment, it's showing:
Array
(
[0] => Array
(
[services/content-writing] => Array
(
[0] => Dashboard\Services#contentwriting
[1] => GET
)
)
[1] => Array
(
[services/pbn-links] => Array
(
[0] => Dashboard\Services#pbnlinks
[1] => GET
)
)
)
The code I'm currently using inside my foreach loop is:
$realArray = array();
// Services exist
if($services)
{
// Sort them into our array
foreach ($services as $service) {
$servicePageName = $service->page_name;
$serviceName = str_replace(' ', '', strtolower($service->name));
$realArrayNew = array(
"services/$servicePageName" => ["Dashboard\Services#$serviceName", 'GET']
);
array_push($realArray, $realArrayNew);
//'home' => ['Dashboard\Main#index', 'GET'],
}
}
return $realArray;
The servicePageName variable must be the key field on the realArray to get the results you want.
I'm presuming you input object array looks something like this:
[
(int) 0 => object(stdClass) {
name => 'contentwriting'
page_name => 'content-writing'
},
(int) 1 => object(stdClass) {
name => 'pbnlinks'
page_name => 'pbn-links'
}
]
If we do this:
$realArray = [];
if ($services) {
foreach ($services as $service) {
$servicePageName = $service->page_name;
$serviceName = str_replace(' ', '', strtolower($service->name));
$realArray["services/$servicePageName"] = [
0 => "Dashboard\Services#$serviceName",
1 => "GET"
];
}
}
This is what we get on realArray:
[
'services/content-writing' => [
(int) 0 => 'Dashboard\Services#contentwriting',
(int) 1 => 'GET'
],
'services/pbn-links' => [
(int) 0 => 'Dashboard\Services#pbnlinks',
(int) 1 => 'GET'
]
]
This portion of the code inserts a new subarray to your main array:
$realArrayNew = array(
"services/$servicePageName" => ["Dashboard\Services#$serviceName", 'GET']
);
array_push($realArray, $realArrayNew);
Replace it all with:
$realArray["services/$servicePageName"] = ["Dashboard\Services#$serviceName", 'GET'];
That way your top level will have service names as keys.

How to count specific value from array PHP?

I have an multidimensional array and I need to count their specific value
Array
(
[0] => Array
(
[Report] => Array
(
[id] => 10
[channel] => 1
)
)
[1] => Array
(
[Report] => Array
(
[id] => 92
[channel] => 0
)
)
[2] => Array
(
[Report] => Array
(
[id] => 18
[channel] => 0
)
)
[n] => Array
)
I need to get output like that: channel_1 = 1; channel_0 = 2 etc
I made a function with foreach:
foreach ($array as $item) {
echo $item['Report']['channel'];
}
and I get: 1 0 0 ... but how can I count it like: channel_1 = 1; channel_0 = 2, channel_n = n etc?
Try this. See comments for step-by-step explanation.
Outputs:
array(2) {
["channel_1"]=>
int(1)
["channel_0"]=>
int(2)
}
Code:
<?php
// Your input array.
$a =
[
[
'Report' =>
[
'id' => 10,
'channel' => 1
]
],
[
'Report' =>
[
'id' => 92,
'channel' => 0
]
],
[
'Report' =>
[
'id' => 18,
'channel' => 0
]
]
];
// Output array will hold channel_N => count pairs
$result = [];
// Loop over all reports
foreach ($a as $report => $values)
{
// Key takes form of channel_ + channel number
$key = "channel_{$values['Report']['channel']}";
if (!isset($result[$key]))
// New? Count 1 item to start.
$result[$key] = 1;
else
// Already seen this, add one to counter.
$result[$key]++;
}
var_dump($result);
/*
Output:
array(2) {
["channel_1"]=>
int(1)
["channel_0"]=>
int(2)
}
*/
You can easily do this without a loop using array_column() and array_count_values().
$reports = array_column($array, 'Report');
$channels = array_column($reports, 'channel');
$counts = array_count_values($channels);
$counts will now equal an array where the key is the channel, and the value is the count.
Array
(
[1] => 1
[0] => 2
)

Merge arrays in an array and add values

I need to take an array like this:
Array
(
[0] => Array
(
[county_code] => 54045
[count] => 218
)
[1] => Array
(
[county_code] => 54045
[count] => 115
)
[2] => Array
(
[county_code] => 54051
[count] => 79
)
)
And merge all arrays with the same county_code adding the count, like this:
Array
(
[0] => Array
(
[county_code] => 54045
[count] => 333
)
[1] => Array
(
[county_code] => 54051
[count] => 79
)
)
There will be multiple instances of multiple county codes.
Can anyone point me in the right direction?
Try this out:
// your example array
$array = [
[
"county_code" => 54045,
"count" => 218
],
[
"county_code" => 54045,
"count" => 115
],
[
"county_code" => 54051,
"count" => 79
]
];
// intrim step to collect the count.
$intrimArray = [];
foreach( $array as $data ){
$countyCode = $data["county_code"];
if (!$intrimArray[$countyCode]) {
$intrimArray[$countyCode] = $data["count"];
} else {
$intrimArray[$countyCode] = $intrimArray[$countyCode] + $data["count"];
}
}
// build the final desired array using interim array.
$finalArray = [];
foreach($intrimArray as $countyCode => $totalCount) {
array_push($finalArray, [
"county_code" => $countyCode,
"count" => $totalCount
]);
}
var_dump($finalArray);
As promised:
<?php
$initial_array = [
['country_code' => 54045, 'count' => 218],
['country_code' => 54045, 'count' => 115],
['country_code' => 54051, 'count' => 79],
];
$synth = [];
foreach ($initial_array as $sa) { # $sa: subarray
if (!isset($synth[$sa['country_code']])) {
$synth[$sa['country_code']] = 0;
}
$synth[$sa['country_code']] += $sa['count'];
}
print_r($synth); # Synthesis array: keys are country codes, values are cumulative counts.
# If you need the same format for both the initial and synthesis arrays, then continue with this:
$synth2 = [];
foreach ($synth as $k => $v) {
$synth2[] = ['country_code' => $k, 'count' => $v];
}
print_r($synth2);
?>
A fiddle for this code: https://3v4l.org/M8tkb
Best regards

Creating a associative array in php from a larger multidimensional array

Im having trouble extracting some information from a large array and placing it in a smaller array, the large array i have is as follows;
Array
(
[0] => Array
(
[BlanketBrand] => Array
(
[BlanketBrandID] => 125
[BlanketBrandName] => Neptune
[BlanketBrandActive] => Y
)
)
[1] => Array
(
[BlanketBrand] => Array
(
[BlanketBrandID] => 126
[BlanketBrandName] => King Size
[BlanketBrandActive] => Y
)
)
)
What i would like is to create an array from this with just the BlanketBrandID as the key and the BlanketBrandName as the value
array(
125 => Neptune,
126 => King Size
)
Something like that so its easier for me to work with.
Any help would be great.
Thanks
This can be done in a very simple foreach loop:
<?php
$array = [
[
'BlanketBrand' => [
'BlanketBrandID' => 125,
'BlanketBrandName' => 'Neptune',
'BlanketBrandActive' => 'Y'
]
],
[
'BlanketBrand' => [
'BlanketBrandID' => 126,
'BlanketBrandName' => 'King Size',
'BlanketBrandActive' => 'Y'
]
]
];
$new_array = [];
foreach ($array as $item) {
$new_array[ $item['BlanketBrand']['BlanketBrandID'] ] = $item['BlanketBrand']['BlanketBrandName'];
}
print_r($new_array);
See example here.
You can also accomplish this with array_reduce():
$new_array = array_reduce($array, function($a, $b) {
$a[ $b['BlanketBrand']['BlanketBrandID'] ] = $b['BlanketBrand']['BlanketBrandName'];
return $a;
}, []);
See example here.

Function result as array value

I checked several similar questions like this, this, and this but remain not clear that, can I get a firm value by operations inside a deep nested array, rather than calling function or assigning a variable?
As an example below to insert at the first position of $arr['row'] depending on $s:
$s = true; //or false;
$arr = [
'key1'=>'val1',
'key2'=>'val2',
'row'=>[
function($s){
if($s) return array('x'=>'y',...);
else return null;
},
[
'row2a'=>'val2a',
'row2b'=>'val2b',
],
[
'row3a'=>'val3a',
'row3b'=>'val3b',
],
],
];
// Output:
Array(
...
[row] => Array
(
[0] => Closure Object
(
[parameter] => Array
(
[$s] =>
)
)
[1] => Array
(
[row2a] => val2a
[row2b] => val2b
)
...
got Closure Object not array('x'=>'y',...) in $arr['row'][0]. Or it's no way to get value by operations inside an array, but calling function or passing by variables? Thanks.
If this is what you need you can always try this approach:
$s = 1;
$value = call_user_func(function($s) { return $s; }, $s);
var_dump($value);
And it will produce:
int(1)
Try below code
$s=true;
function abc($flag) {
if ($flag):
$array["x"]="x";
$array["y"]="y";
return $array;
else:
return null;
endif;
}
$arr = [
'key1' => 'val1',
'key2' => 'val2',
'row' => [
$resultset = abc($s),
[
'row2a' => 'val2a',
'row2b' => 'val2b',
],
[
'row3a' => 'val3a',
'row3b' => 'val3b',
],
],
];
print_r($arr);
exit;
output
Array
(
[key1] => val1
[key2] => val2
[row] => Array
(
[0] => Array
(
[x] => x
[y] => y
)
[1] => Array
(
[row2a] => val2a
[row2b] => val2b
)
[2] => Array
(
[row3a] => val3a
[row3b] => val3b
)
)
)

Categories