1

I have array data like this

 Array(
 [0] => stdClass Object
        ([iditem] => 31702152
         [idcolor] => 39 )
 [1] => stdClass Object
        ([iditem] => 31702152
        [idcolor] => 38))

So I want to put each idcolor to new variable $colorid and the result are 38,39. I can't find match keyword, or can I get the link of similar question ?

2

4 Answers 4

1

You can use array_map which map/return the new array as it was designed to this kind of job, supposed this :

// creating array of object
$a = (object) array('iditem' => 31702151,'idcolor' => 38 );
$b = (object) array('iditem' => 31702152,'idcolor' => 39 );
// placing above data to new array container
$ab = array($a,$b);

// callback function
function getData( $obj ) {
  return $obj->idcolor;
}

// array_map the array using above callback
$colorid = array_map("getData", $ab );

print_r( $colorid );

Above code will produce Array( [0] => 39, [1] => 38 ). If you want it value directly stored in variable as a single string separate it by commas, just use the implode function to do so :

$newStr = implode(',', $colorid );
// which will produce 38,39
Sign up to request clarification or add additional context in comments.

Comments

0

Using Array implementation and implode

$ids = [];
foreach($youarray as $value) {
    $ids[] = $value->idcolor;
}

$finalIds = implode(',', $ids);

Using string concatenation and rtrim

$finalIds = '';
foreach($youarray as $value) {
    $finalIds = $value->idcolor.',';
}

$finalIds = rtrim($finalIds, ',');

Comments

0

So you want $colorid to be an array with all the ids if I understand correctly right?

$colorid = array();

foreach($array as $object)
    array_push($colorid, $object->idcolor);

Comments

0

You may use array_reduce for the job:

<?php

// your data
$data = array(
  (object) array('iditem' => 31702152, 'idcolor' => 39),
  (object) array('iditem' => 31702152, 'idcolor' => 38),
);

// the code
$output = array_reduce($data, function($carry, $obj) {
  if (isset($obj->idcolor)) $carry[] = $obj->idcolor;
  return $carry;
}, array());
sort($output); // directly sort the $output variable

$output will be:

array(38, 39);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.