PHP - how to search ID and display its value in a object - php

Hi I have an array of object like this
$json = json_decode($featureJson);
//which returns below
Array
(
[0] => stdClass Object
(
[productID] => 1
[productName] => Toyo
[assessments] => Array
(
[0] => stdClass Object
(
[answer] => Yes
)
[1] => stdClass Object
(
[answer] => Yes
)
...
)
)
[1] => stdClass Object
(
[productID] => 2
[productName] => Maze
[assessments] => Array
(
[0] => stdClass Object
(
[answer] => Yes
)
[1] => stdClass Object
(
[answer] => Yes
)
...
)
)
)
and I have another array that needs to match the ID of $json(Array of Objects) and return its productName.
$string = "1,2|2,1";
$IdArray = explode('|', $string);
$foo = '';
foreach ($IdArray as $item) {
$foo .= '{' . $item . '},';
}
echo $foo;
$foo return {1,2},{2,1} and I match $json so will display - {Toyo,Maze},{Maze,Toyo}, how can I do that? I have some hint using array_map()
but still got no idea to match in objects.

It's easier if you separate an array for the names first.
<?php
$featureJson = '[{"productID":1,"productName":"Toyo","assessments":[{"answer":"Yes"},{"answer":"No"}]},{"productID":2,"productName":"Maze","assessments":[{"answer":"Yes"},{"answer":"Yes"}]}]';
$json = json_decode($featureJson);
// Make an array of names
$names = [];
foreach($json as $products){
$names[$products->productID] = $products->productName;
};
$string = "1,2|2,1";
$IdArray = explode('|', $string);
$foo = [];
foreach ($IdArray as $ids) {
$ids = explode(',',$ids);
$fooItem = [];
foreach($ids as $id){
$fooItem[] = $names[$id];
}
$foo[]= '{' . implode(',',$fooItem) . '}'; }
echo implode(',',$foo);
Result:
{Toyo,Maze},{Maze,Toyo}
Check here

Related

group array of php objects and sum by object key

I have an array of php objects that looks something like this:
Array
(
[0] => stdClass Object
(
[order_id] => 1513
[order_total] => 12500.00
[sales_rep] => Doe_John
)
[1] => stdClass Object
(
[order_id] => 1046
[order_total] => 3300.00
[sales_rep] => Doe_John
)
[2] => stdClass Object
(
[order_id] => 337
[order_total] => 4500.00
[sales_rep] => Mosby_Ted
)
)
I am trying to get an array that is set up more like this:
Array
(
[0] => stdClass Object
(
[sales_rep] => Doe_John
[total_sales] => 15800.00
)
[1] => stdClass Object
(
[sales_rep] => Mosby_Ted
[total_sales] => 4500.00
)
)
I want to combine all of the objects with the same "sales_rep" and get the sum of their associated "order_total", which you can see an example of in my desired array above. Any thoughts on how to accomplish this? I've been at it for hours now and have not been able to figure out a solution.
Thanks so much for the help!
try this
$tmp = array();
foreach($objs as $obj){ // where `$objs` is your objects
if(!in_array($obj->sales_rep,array_keys($tmp))){
$tmp[$obj->sales_rep] = (object)array(
'sales_rep' => $obj->sales_rep,
'total_sales' => $obj->order_total
);
}else{
$tmp[$obj->sales_rep]->total_sales += $obj->order_total;
}
}
print_r(array_values($tmp));
$obj0 = new StdClass();
$obj0->order_id = 1513;
$obj0->order_total = 12500.00;
$obj0->sales_rep = 'Doe_John';
$obj1 = new StdClass();
$obj1->order_id = 1046;
$obj1->order_total = 3300.00;
$obj1->sales_rep = 'Doe_John';
$obj2 = new StdClass();
$obj2->order_id = 337;
$obj2->order_total = 4500.00;
$obj2->sales_rep = 'Mosby_Ted';
$array = array(
$obj0,
$obj1,
$obj2,
);
$newArray = array();
foreach ($array as $item) {
if (array_key_exists($item->sales_rep, $newArray)) {
$newObj = $newArray[$item->sales_rep];
$newObj->order_total += $item->order_total;
} else {
$newObj = new StdClass();
$newObj->sales_rep = $item->sales_rep;
$newObj->order_total = $item->order_total;
$newArray[$newObj->sales_rep] = $newObj;
}
}
print_r(array_values($newArray));

how to put a different objects inside each array element of an array in php?

I have two arrays, e.g
$mainArray = array('a','b','c','d','e','f','g');
$subArray = it contains an array of objects e.g
array( objec1, objec2, object3, object4) ...
within each of the objects, holds the value that matches one of the keys in the
$mainArray.
my Question now is, how am i gonna match and put the correct objects to the mainArray, so that
it should appear like this e.g
$mainArray = array('a'=> array(object3,object2), 'b' => array(object4,object1));
$result = array();
foreach ($subArray as $obj) {
if (!isset($result[$obj->keyOfMainArray])) {
$result[$obj->keyOfMainArray] = array();
}
$result[$obj->keyOfMainArray][] = $obj;
}
Assuming val is your object's property
$mainArray = array('a','b','c','d','e','f','g');
$subArray = array(...);
$result = array();
foreach($subArray as $object) {
$result[$object->val][] = $object;
}
Example result
Array
(
[a] => Array
(
[0] => stdClass Object
(
[val] => a
)
[1] => stdClass Object
(
[val] => a
)
)
[b] => Array
(
[0] => stdClass Object
(
[val] => b
)
)
)

Create array of objects with individual values from an array of objects containing comma-delimited values

Here, I have the following variable $countries_all:
Array (
[0] => stdClass Object
(
[countries] => India,Afghanestan,Japan,South Africa
)
[1] => stdClass Object
(
[countries] => Singapore,South Africa,India,Pakistan
)
[2] => stdClass Object
(
[countries] => Japan,Australia,India
)
)
But i need to create second array $countries containing only unique values:
Array (
[0] => stdClass Object
(
[countries] => India
)
[1] => stdClass Object
(
[countries] => Afghanestan
)
[2] => stdClass Object
(
[countries] => Japan
)
[3] => stdClass Object
(
[countries] => South Africa
)
[4] => stdClass Object
(
[countries] => Singapore
)
[5] => stdClass Object
(
[countries] => Pakistan
)
[6] => stdClass Object
(
[countries] => Japan
)
[7] => stdClass Object
(
[countries] => Australia
)
)
For splitting by (,) I have used the below method
foreach ($countries_all as $list){
$countrieslist=explode(',', $list->countries);
foreach ($countrieslist as $uni_countries){
echo $uni_countries;
}
}
but how to get unique values?
The array_unique function is what you are looking for.
$countries = array();
foreach ($countries_all as $list){
$countrieslist=explode(',', $list->countries);
foreach ($countrieslist as $country){
$countries[] = $country;
}
}
$countries = array_unique($countries);
$newlist = array();
foreach ($countries_list as $list){
$countrieslist=explode(',', $list->countries);
foreach ($countrieslist as $uni_countries){
echo $uni_countries;
$newlist[] = $uni_countries){
}
}
array_unique($newlist);
$commasplit = function ($list) { return explode(',', $list->countries); };
$countrieslist = array_unique(call_user_func_array('array_merge', array_map($commasplit, $countries_list)));
You may try this
$countrieslist = array();
foreach ($countries_all as $list){
$countrieslist[] = explode(',', $list->countries);
}
$array = array_unique(array_reduce($countrieslist,'array_merge', array()));
An Example.
Try this:
$uniqueCountries = array();
foreach ($countries_list as $list){
$countrieslist=explode(',', $list->countries);
foreach ($countrieslist as $country){
if (!in_array($country, $uniqueCountries)) {
//adding to list
$uniqueCountries[] = $country
} else {
echo $country, ' already in list', PHP_EOL;
}
}
}
$uniqueCoutries contains all found coutries, without duplicates
Instead of asking array_unique or in_array() to perform extra cycles to weed out the duplicates, don't let the duplicate values in in the first place. You can rely on PHP's refusal to have duplicate keys in the same level of an array.
By assigning the single country value not only as the object property, but also as the first level key, you ensure that there be no duplication even if the same country is encountered again while iterating.
This technique will perform faster than earlier posted techniques on this page.
If you don't want the first level keys after iterating, you can re-index the array with array_values().
Code: (Demo)
$result = [];
foreach ($array as $obj) {
foreach (explode(',', $obj->countries) as $country) {
$result[$country] = (object) ['countries' => $country];
}
}
var_export(array_values($result));

stdClass object array inside of another array

I'm trying to get information from the $array1 below.
I'm getting with no problems venue's name and location address by doing:
$array2 = array();
$array3 = array();
foreach($array1 as $item){
$array2[] = $item->venue->name;
$array3[] = $item->venue->location->address;
}
But now I need to get the photos url and I don't know how to do it.
Thanks a million!
$array1:
Array
(
[0] => stdClass Object
(
[venue] => stdClass Object
(
[name] => a name
[location] => stdClass Object
(
[address] => main street
)
)
[photos] => stdClass Object
(
[count] => 1
[items] => Array
(
[0] => stdClass Object
(
[url] => http://folder/photo1.jpg
.
.
)))
.
.
$array1[0]->photos->items[0]->url
Remember - you access arrays with [index] parenthesis, objects with -> arrows.
Untested code:
$array2 = array();
$array3 = array();
$photos = array();
foreach($array1 as $item){
$array2[] = $item->venue->name;
$array3[] = $item->venue->location->address;
$item_photo_urls = array();
foreach($item->photos->items as $photo){
$item_photo_urls[] = $photo->url;
}
$photos[] = $item_photo_urls;
}
Now you have a third array called photos , which contains all the photo urls.
Try this :
$url = $item->photos->items[0]->url;

How can I create multidimensional arrays from a string in PHP?

So My problem is:
I want to create nested array from string as reference.
My String is "res[0]['links'][0]"
So I want to create array $res['0']['links']['0']
I tried:
$result = "res[0]['links'][0]";
$$result = array("id"=>'1',"class"=>'3');
$result = "res[0]['links'][1]";
$$result = array("id"=>'3',"class"=>'9');
when print_r($res)
I see:
<b>Notice</b>: Undefined variable: res in <b>/home/fanbase/domains/fanbase.sportbase.pl/public_html/index.php</b> on line <b>45</b>
I need to see:
Array
(
[0] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 1
[class] => 3
)
)
)
[1] => Array
(
[links] => Array
(
[0] => Array
(
[id] => 3
[class] => 9
)
)
)
)
Thanks for any help.
So you have a description of an array structure, and something to fill it with. That's doable with something like:
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
// unoptimized, always uses strings
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
array_create( $res, "[0]['links'][0]", array("id"=>'1',"class"=>'3') );
array_create( $res, "[0]['links'][1]", array("id"=>'3',"class"=>'9') );
Note how the array name itself is not part of the structure descriptor. But you could theoretically keep it. Instead call the array_create() function with a $tmp variable, and afterwards extract() it to achieve the desired effect:
array_create($tmp, "res[0][links][0]", array(1,2,3,4,5));
extract($tmp);
Another lazy solution would be to use str_parse after a loop combining the array description with the data array as URL-encoded string.
I have a very stupid way for this, you can try this :-)
Suppose your string is "res[0]['links'][0]" first append $ in this and then put in eval command and it will really rock you. Follow the following example
$tmp = '$'.'res[0]['links'][0]'.'= array()';
eval($tmp);
Now you can use your array $res
100% work around and :-)
`
$res = array();
$res[0]['links'][0] = array("id"=>'1',"class"=>'3');
$res[0]['links'][0] = array("id"=>'3',"class"=>'9');
print_r($res);
but read the comments first and learn about arrays first.
In addition to mario's answer, I used another function from php.net comments, together, to make input array (output from jquery form serializeArray) like this:
[2] => Array
(
[name] => apple[color]
[value] => red
)
[3] => Array
(
[name] => appleSeeds[27][genome]
[value] => 201
)
[4] => Array
(
[name] => appleSeeds[27][age]
[value] => 2 weeks
)
[5] => Array
(
[name] => apple[age]
[value] => 3 weeks
)
[6] => Array
(
[name] => appleSeeds[29][genome]
[value] => 103
)
[7] => Array
(
[name] => appleSeeds[29][age]
[value] => 2.2 weeks
)
into
Array
(
[apple] => Array
(
[color] => red
[age] => 3 weeks
)
[appleSeeds] => Array
(
[27] => Array
(
[genome] => 201
[age] => 2 weeks
)
[29] => Array
(
[genome] => 103
[age] => 2.2 weeks
)
)
)
This allowed to maintain numeric keys, without incremental appending of array_merge. So, I used sequence like this:
function MergeArrays($Arr1, $Arr2) {
foreach($Arr2 as $key => $Value) {
if(array_key_exists($key, $Arr1) && is_array($Value)) {
$Arr1[$key] = MergeArrays($Arr1[$key], $Arr2[$key]);
}
else { $Arr1[$key] = $Value; }
}
return $Arr1;
}
function array_create(&$target, $desc, $fill) {
preg_match_all("/[^\[\]']+/", $desc, $uu);
foreach ($uu[0] as $sub) {
if (! isset($target[$sub])) {
$target[$sub] = array();
}
$target = & $target[$sub];
}
$target = $fill;
}
$input = $_POST['formData'];
$result = array();
foreach ($input as $k => $v) {
$sub = array();
array_create($sub, $v['name'], $v['value']);
$result = MergeArrays($result, $sub);
}

Categories